Java: Generic methods and numbers

Viewed 7437

I want to make a generic method which makes the total sum of a List of numbers.

What I was trying is this:

public static <T extends Number> T sumList(List<T> data)
{
    T total = 0;
    for (T elem : data)
    {
        total += elem;
    }
    return total;
}

But the problem is that there is no += operator in T and that total can't be assigned to zero.

How can I do this?

Thanks

4 Answers

You can use a library, such as Generic Java Math (its numbers part), which provides generic operations for Number subclasses. It provides a way to work generically with numbers, just as in your example, but with passing Arithmetics object around, that does the actual calculation. See example on the home page.
It must use boxed types, so if you need speed, no generic implementation can do that in Java, you must use primitive types.

Related