如何编写添加数字的通用方法 [英] how to write a generic method for adding numbers
问题描述
我想定义一种方法来在
不同类型数字之间进行总和:
< T> void add(T one,T two)
{
T res = one + two;
$ / code>
上面的方法不起作用,因为type erasure convert 如何才能做到这一点? 谢谢。 请注意,它使用double作为返回类型,因为这是覆盖原始数字类型值的最大范围 - 一个或两个参数也可以是 I want to define a method to make sums between
different type numbers: the above method not work because type erasure convert How can do that? Thanks. You'll have to use a bounded type parameter: Note that it uses double as return type because that's the primitive numeric type that covers the largest range of values - and one or both parameters could be 这篇关于如何编写添加数字的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! T 转换为
对象
,因此+操作符未在 Object
中定义。 ..
public> < T扩展数字> double add(T one,T two)
{
return one.doubleValue()+ two.doubleValue();
$ b double
。请注意, Number
还具有 BigDecimal
和 BigInteger
作为子类,它可以代表 double
范围之外的值。如果你想正确处理这些情况,它会使方法变得更加复杂(你必须开始处理不同类型的不同类型)。<T> void add (T one, T two)
{
T res = one + two;
}
T
into Object
and thus the + operator is not defined on Object
...public <T extends Number> double add (T one, T two)
{
return one.doubleValue() + two.doubleValue();
}
double
too. Note that Number
also has BigDecimal
and BigInteger
as subclasses, which can represent values outside the range of double
. If you want to handle those cases correctly, it would make the method a lot more complex (you'd have to start handling different types differenty).