Eli Sadoff - 4 months ago 33

Java Question

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>`

`Vector<T>`

`T[] data`

`Class<T> klass`

`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`

`Vector<T>`

`private static Number add(Number a, T b) {`

return (Number)(a.intValue() + ((Number) b).intValue());

}

However, this

`add`

`Number`

`Number`

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.