我可以对 Number 基类进行算术运算吗? [英] Can I do arithmetic operations on the Number baseclass?

查看:35
本文介绍了我可以对 Number 基类进行算术运算吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 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

我认为通过添加扩展数字"代码可以编译.是否可以执行此 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 没有 + 操作符与之关联,也没有操作符重载.

Number does not have a + operator associated with it, nor can it since there is no operator overloading.

不过这样就好了.

基本上,您要求 java 自动装箱 Number 的后代,它恰好包括 Integer、Float 和 Double,可以自动装箱并应用加号运算符,但是,可能有任意数量的 Number 的其他未知后代不能被自动装箱,直到运行时才能知道.(该死的擦除)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆