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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With