I want to define a method to make sums between different type numbers:
<T> void add (T one, T two)
{
T res = one + two;
}
the above method not work because type erasure convert T
into Object
and thus the + operator is not defined on Object
...
How can do that?
Thanks.
You'll have to use a bounded type parameter:
public <T extends Number> double add (T one, T two)
{
return one.doubleValue() + two.doubleValue();
}
Note that it uses double as return type because that's the primitive numeric type that covers the largest range of values - and one or both parameters could be double
too. Note that Number
also has BigDecimal
and BigInteger
as subclasses, which can represent values outside the range of double
. If you want to handle those cases correctly, it would make the method a lot more complex (you'd have to start handling different types differenty).
The "simplest" solution I can think of is this (excuse the casting and auto-boxing/unboxing):
@SuppressWarnings("unchecked")
<T> T add(T one, T two) {
if (one.getClass() == Integer.class) {
// With auto-boxing / unboxing
return (T) (Integer) ((Integer) one + (Integer) two);
}
if (one.getClass() == Long.class) {
// Without auto-boxing / unboxing
return (T) Long.valueOf(((Long) one).longValue() +
((Long) two).longValue());
}
// ...
}
Add as many types you want to support. Optionally, you could handle null
as well...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With