I need to create a helper method which allows to create a sum of any Iterable<? extends Number>, because we have many vectors and require a fast method to determine the sum, so I created the following method:
static Integer sum(Iterable<Integer> it) {
Integer result = 0;
for(T next : it) {
result += next;
}
return result;
}
This method only works for ints however, but we also have doubles and longs. Because you can't have two methods with the same signature (Our compiler thinks Integer sum(Iterable<Integer>) has the same signature as Double sum(Iterable<Double>).) I tried to write one method with generics.
private static <T extends Number> T sum(Iterable<? extends T> it) {
T result;
for(T next : it) {
result += next;
}
return result;
}
However this method will not compile (reason: the operator += is undefined for Object, Object). What can I do here? I know in C++ you can overload operators, but not in Java. But every class which extends Number does overload the += operator. What can I do here?
Thank you in advance.