使用泛型类来执行基本的算术运算 [英] Using a generic class to perform basic arithmetic operations

查看:136
本文介绍了使用泛型类来执行基本的算术运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对包装类型(比如 Integer )使用一个通用方法来执行像加法,减法,乘法和除法等基本算术运算。 Float Double ...(不包括 BigDecimal BigInteger



我尝试使用泛型类来做类似下面的事情(用于添加)。

  public final class GenericClass< E extends Number> {

public E add(E x,E y){
return x + y; //编译时错误
}
}

时间错误,


operator +不能应用于E,E


有没有办法使用这样的通用版本来实现这样的操作?

不是这样做的方式,否则它将被构建到Java中。类型系统不足以表达此类事物。


I want to perform basic arithmetic operations like addition, subtraction, multiplication and division using only one generic method per operation for wrapper types like Integer, Float, Double ... (excluding BigDecimal and BigInteger).

I have tried to do something like the following (for addition) using a generic class.

public final class GenericClass<E extends Number> {

    public E add(E x, E y) {
        return x + y; // Compile-time error
    }
}

It issues a compile-time error,

operator + cannot be applied to E,E

Is there a way to use such a generic version to achieve such operations?

解决方案

No, there isn't a way to do this, or else it would be built into Java. The type system isn't strong enough to express this sort of thing.

这篇关于使用泛型类来执行基本的算术运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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