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:
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
doubletoo. Note thatNumberalso hasBigDecimalandBigIntegeras subclasses, which can represent values outside the range ofdouble. 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).