Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write a generic method for adding numbers [duplicate]

Tags:

java

generics

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.

like image 294
xdevel2000 Avatar asked Aug 12 '11 09:08

xdevel2000


2 Answers

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).

like image 184
Michael Borgwardt Avatar answered Oct 13 '22 03:10

Michael Borgwardt


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

like image 13
Lukas Eder Avatar answered Oct 13 '22 03:10

Lukas Eder