java 泛型参数 运算,如何在Java中使用泛型和语言运算符以及扩展Number的泛型类...

I would like to perform an operation on two generics argument of the same type both extending Number.

Is it Possible?

I always used to call methods on generic arguments, but seems there is some problem using operators (The operator + is undefined for the argument type(s) T, T).

public static T sum(T a, T b){

return a+ b;

}

What am I doing wrong?

EDIT:

I try to improve a little bit my question. I understood that operators are not defined for type Number. It's a bit sad this thing because it would be nice to perform such an operation without introducing new interfaces like suggested by @Victor Sorokin.

But I still don't understand one thing: if operators are not implemented in the class Number, then at least in Double class should be implemented because I can use + operator with double.

Neither these line of code will compile:

public static T sum(T a, T b){

T c = a +b;

}

why?

解决方案

It's not possible because Number doesn't have a + operator associated with it. In particular, you can't do this:

Number a = new Integer(1);

Number b = new Integer(2);

Number c = a + b;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值