Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

Java: Generic methods and numbers

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...