我可以对Number基类进行算术运算吗?

我试图在Java中创建一个通用类,该通用类将对数字进行运算。在以下示例中,添加如下:


public class Example <T extends Number> {


    public T add(T a, T b){

        return a + b;

    }


}

原谅我的天真,因为我是Java Generics的新手。此代码无法编译并显示以下错误:


未为参数类型T,T定义运算符+


我以为,加上“扩展数字”,代码便可以编译。是否可以使用此Java,还是必须为每种Number类型创建重写的方法?


www说
浏览 517回答 3
3回答

largeQ

Number没有关联的+运算符,也没有,因为没有运算符重载。那就太好了。基本上,您是在要求Java自动对Number的后代进行自动装箱,该后代恰好包括Integer,Float和Double,可以自动装箱并应用加号运算符,但是,可能有Number的许多其他未知后代无法自动装箱,直到运行时才能知道。(该死的删除)

慕仙森

您的问题与泛型并没有真正的关系,而是与运算符,原语与对象以及自动装箱有关。考虑一下:public static void main(String[] args) {&nbsp; &nbsp; Number a = new Integer(2);&nbsp; &nbsp; Number b = new Integer(3);&nbsp; &nbsp; Number c = a + b;}上面没有编译public static void main(String[] args) {&nbsp; &nbsp; Integer&nbsp; a = new Integer(2);&nbsp; &nbsp; Integer b = new Integer(3);&nbsp; &nbsp; Number c = a + b;}上面的代码确实可以编译,但这仅是由于自动装箱-这是Java 5中引入的一种骇人听闻的语法胶,并且仅在某些具体类型下(在编译时)有效,例如int-Integer。在后台,Java编译器正在重写最后一条语句(“我必须取消装箱a并b应用具有原始数据类型的sum运算符,然后将结果装箱以将其分配给对象c”),因此:&nbsp; &nbsp; Number c = Integer.valueOf( a.intValue() + b.intValue() );Java无法解包a,Number因为它在编译时不知道具体类型,因此无法猜测其原始对应物。

森栏

是的,内森是正确的。如果您想要这样的东西,您必须自己编写public class Example <T extends Number> {&nbsp; &nbsp; private final Calculator<T> calc;&nbsp; &nbsp; public Example(Calculator<T> calc) {&nbsp; &nbsp; &nbsp; &nbsp;this.calc = calc;&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; public T add(T a, T b){&nbsp; &nbsp; &nbsp; &nbsp; return calc.add(a,b);&nbsp; &nbsp; }}public interface Calculator<T extends Number> {&nbsp; &nbsp; public T add(T a, T b);}public class IntCalc implements Calculator<Integer> {&nbsp; &nbsp; public final static IntCalc INSTANCE = new IntCalc();&nbsp; &nbsp; private IntCalc(){}&nbsp; &nbsp; public Integer add(Integer a, Integer b) { return a + b; }}...Example<Integer> ex = new Example<Integer>(IntCalc.INSTANCE);System.out.println(ex.add(12,13));太糟糕了,Java没有类型类(Haskell)或隐式对象(Scala),此任务将是一个完美的用例...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java