如何在 Java 中使用泛型与语言运算符和扩展 Number 的泛型类
我想对两个相同类型的泛型参数执行操作,这两个参数都扩展了 Number。
是否可以? 我总是习惯于在泛型参数上调用方法,但使用运算符似乎存在一些问题(对于参数类型 T, T ,运算符 + 未定义)。
public static <T extends Number> T sum(T a, T b){
return a+ b;
}
我做错了什么?
编辑: 我尝试改进一下我的问题。我知道运算符没有为 Number 类型定义。这件事有点令人难过,因为如果不引入@Victor Sorokin 建议的新接口就可以执行这样的操作,那就太好了。
但我仍然不明白一件事:如果 Number 类中没有实现运算符,那么至少应该在 Double 类中实现,因为我可以将 + 运算符与 double 一起使用。 这行代码都无法编译:
public static <T extends Double> T sum(T a, T b){
T c = a +b;
}
为什么?
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 extends Number> 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 extends Double> T sum(T a, T b){
T c = a +b;
}
why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是不可能的,因为
Number
没有与之关联的 + 运算符。特别是,你不能这样做:It's not possible because
Number
doesn't have a + operator associated with it. In particular, you can't do this:Java 中的类没有
+
运算符(String 除外,当参数之一是 String 时,可以通过toString()
隐式转换其他类型)。那么,让你输入实现一些接口,比如丑陋的,不是吗? =D
上面的 Fix 2022 代码是错误的,因为
Valuable#value
无法生成子类型T
的实例,所以我们需要稍微修改一下多毛:There is no
+
operator for classes in Java (except String and there's implicit conversion for other types viatoString()
when one of arguments is String). So, make you type implement some interface, sayUgly, isn't it? =D
Fix 2022 code above is wrong, as
Valuable#value
can't produce instance of subtypeT
, so we need to go a bit more hairy: