我想对包装类型(比如 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.
更多推荐
使用泛型类来执行基本的算术运算
发布评论