Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Generic methods and numbers

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

like image 410
Martijn Courteaux Avatar asked Oct 03 '10 18:10

Martijn Courteaux


People also ask

How do you write a generic method for adding numbers?

getClass() == Integer. class) { // With auto-boxing / unboxing return (T) (Integer) ((Integer) one + (Integer) two); } if (one. getClass() == Long. class) { // Without auto-boxing / unboxing return (T) Long.

What is generic method in Java?

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.


1 Answers

There are ways you can hack this together but in all honestly, generics is simply not the way to go here. Build a method for each concrete primitive wrapper type and implement them separately. It'll be way too much of a headache to make it generic; arithmetic operations can't happen generically.

You don't really gain anything by making it generic, either. It's such simple and constant code that you aren't worried about code duplication, since it's not going to change. And people aren't going to be passing in their own type of Number to your code; the domain of types it applies to is already well defined and finite.

like image 184
Mark Peters Avatar answered Oct 20 '22 00:10

Mark Peters