使用泛型类来执行基本的算术运算

编程入门 行业动态 更新时间:2024-10-21 06:06:29
本文介绍了使用泛型类来执行基本的算术运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想对包装类型(比如 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.

更多推荐

使用泛型类来执行基本的算术运算

本文发布于:2023-11-16 23:58:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608047.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算术   泛型类来

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!