Eli Sadoff Eli Sadoff - 1 year ago 86
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

class, I am having a problem with summing the elements. My class
has attributes
T[] data
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
which is also in

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download