如何编写添加数字的通用方法 [英] how to write a generic method for adding numbers

查看:90
本文介绍了如何编写添加数字的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一种方法来在
不同类型数字之间进行总和:

 < T> void add(T one,T two)
{
T res = one + two;

$ / code>

上面的方法不起作用,因为type erasure convert T 转换为对象
,因此+操作符未在 Object 中定义。 ..

如何才能做到这一点?



谢谢。



  public> 

< T扩展数字> double add(T one,T two)
{
return one.doubleValue()+ two.doubleValue();





$ b

请注意,它使用double作为返回类型,因为这是覆盖原始数字类型值的最大范围 - 一个或两个参数也可以是 double 。请注意, Number 还具有 BigDecimal BigInteger 作为子类,它可以代表 double 范围之外的值。如果你想正确处理这些情况,它会使方法变得更加复杂(你必须开始处理不同类型的不同类型)。


I want to define a method to make sums between different type numbers:

<T> void add (T one, T two)
{
    T res = one + two; 
}

the above method not work because type erasure convert T into Object and thus the + operator is not defined on Object...

How can do that?

Thanks.

解决方案

You'll have to use a bounded type parameter:

public <T extends Number> double add (T one, T two)
{
    return one.doubleValue() + two.doubleValue(); 
}

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 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).

这篇关于如何编写添加数字的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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