开发者

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

This question already has answers here: Java Generics and adding numbers together (9 answers) Closed 9 years ago.

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 wo开发者_如何转开发rk 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...


Look at this discussion on SO: How to add two java.lang.Numbers?

It's about the same as your problem. Either way, you should not use generics for this, why? Simple: because with generics you couldn't add a Float and a Double, which in general you should be able to do!


template <class A>
A add (A a, A b)
{
    return (a+b);

}
int main()
{
    int x =10, y =20;
    cout <<"The Integer Addition is " << add(x,y);
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜