Java: Using generics to implement a class that operates on different kinds of numbers


So, let's say I want to write a class that operates on different kinds of numbers, but I don't a priori know what kind of numbers (i.e. ints, doubles, etc.) I will be operating on.

I would like to use generics to create a general class for this scenario. Something like:

 Adder<Double> adder = new Adder<Double>();
 adder.add(10.0d, 10.0d);   // = 20.0d

But, I cannot instantiate the generic type I pass in to my Adder class! So — what to do?

Best Solution

Uh oh---generics are not C++ templates. Because of type erasure, the Double in your example won't even show through to the runtime system.

In your particular case, if you just want to be able to add various types together, may I suggest method overloading? e.g., double add(double, double), float add(float, fload), BigDecimal add(BigDecimal, BigDecimal), etc.