Java:通用方法和数字 [英] Java: Generic methods and numbers

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

问题描述

我想创建一个通用方法,它使得 List 数字的总和。



我试图这样做:

  public static< T extends Number> T sumList(List< T> data)
{
T total = 0; (T元素:数据)
{
total + = elem;

}
总回报;
}

但问题在于没有+ =运算符在T 中,并且 total不能指定为零



我可以这样做吗?

谢谢

解决方案

可以一起破解这一切,但实际上,仿制药根本就不是这里的出路。为每个具体原始包装类型构建一个方法并分别实现它们。让它变得通用会让人头痛不已;算术运算不能一般发生。

无论如何,你都没有真正获得任何东西。它是如此简单而不变的代码,您不会担心代码重复,因为它不会改变。人们不会将自己的数字类型传递给您的代码;它适用的类型的领域已经很好地定义和有限。

I want to make a generic method which makes the total sum of a List of numbers.

What I was trying is this:

public static <T extends Number> T sumList(List<T> data)
{
    T total = 0;
    for (T elem : data)
    {
        total += elem;
    }
    return total;
}

But the problem is that there is no += operator in T and that total can't be assigned to zero.

How can I do this?

Thanks

解决方案

There are ways you can hack this together but in all honestly, generics is simply not the way to go here. Build a method for each concrete primitive wrapper type and implement them separately. It'll be way too much of a headache to make it generic; arithmetic operations can't happen generically.

You don't really gain anything by making it generic, either. It's such simple and constant code that you aren't worried about code duplication, since it's not going to change. And people aren't going to be passing in their own type of Number to your code; the domain of types it applies to is already well defined and finite.

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

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