I want to perform basic arithmetic operations like addition, subtraction, multiplication and division using only one generic method per operation for wrapper types like Integer
, Float
, Double
… (excluding BigDecimal
and BigInteger
).
I have tried to do something like the following (for addition) using a generic class.
public final class GenericClass<E extends Number> { public E add(E x, E y) { return x + y; // Compile-time error } }
It issues a compile-time error,
operator + cannot be applied to E,E
Is there a way to use such a generic version to achieve such operations?
Advertisement
Answer
No, there isn’t a way to do this, or else it would be built into Java. The type system isn’t strong enough to express this sort of thing.