我可以对Number基类进行算术运算吗? [英] Can I do arithmetic operations on the Number baseclass?
问题描述
我正在尝试在Java中创建一个将对数字执行操作的泛型类。在以下示例中,添加如下:
I am trying to create a generic class in Java that will perform operations on numbers. In the following example, addition, as follows:
public class Example <T extends Number> {
public T add(T a, T b){
return a + b;
}
}
原谅我的天真,因为我是相对的Java泛型的新手。此代码无法使用错误进行编译:
Forgive my naivety as I am relatively new to Java Generics. This code fails to compile with the error:
参数类型的运算符+未定义T,T
The operator + is undefined for the argument type(s) T, T
我认为通过添加extends Number,代码将被编译。是否可以执行此Java或我是否必须为每个Number类型创建重写方法?
I thought that with the addition of "extends Number" the code would compile. Is it possible to do this Java or will I have to create overridden methods for each Number type?
推荐答案
数字没有+运算符与它关联,也不能,因为没有运算符重载。
Number does not have a + operator associated with it, nor can it since there is no operator overloading.
虽然会很好。
基本上,你要求java自动装备一个数字的目标,其中包括Integer,Float和Double,它们可能被自动装箱并且应用了一个加号运算符,但是,可能有任何数量的其他未知的数字后代不能自动装箱,直到运行时才能知道。 (该死的擦除)
Basically, you are asking java to autobox a descedant of Number which happens to include Integer, Float and Double, that could be autoboxed and have a plus operator applied, however, there could be any number of other unknown descendants of Number that cannot be autoboxed, and this cannot be known until runtime. (Damn erasure)
这篇关于我可以对Number基类进行算术运算吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!