Eli Sadoff Eli Sadoff - 1 month ago 6
Java Question

Adding Generic Numbers in Java

I'm working on an algebraic library in Java that optimizes certain matrix calculations and reductions. I have been using generics relatively successfully thus far, but within my

Vector<T>
class, I am having a problem with summing the elements. My class
Vector<T>
has attributes
T[] data
and
Class<T> klass
. The summation method I have right now is like this

public Number sum() throws ArithmeticException {
if (getKlass().isInstance(Number.class)) {
Number sum = 0;
for (T t : getData())
sum = add(sum, t);
return sum;
} else {
throw new ArithmeticException("Generic type T is not an instance of Number");
}
}


This relies on the method
add
which is also in
Vector<T>


private static Number add(Number a, T b) {
return (Number)(a.intValue() + ((Number) b).intValue());
}


However, this
add
method leaves a lot to be desired. Is there a better way to add
Number
s together, especially one that does not cause huge truncation issues by converting every
Number
to a primitive type?

Answer

Number is not a very useful base class. It's difficult to work with numbers generically in Java.

It's why there are so many places in the standard library where the language designers created int/long/float/double specializations by hand. I recommend you do the same. The code duplication is unfortunate, but it's common practice.

On the upside, it will let you avoid boxing and unboxing. If performance is important, that's crucial.