Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics and adding numbers together

Tags:

java

generics

I would like to generically add numbers in java. I'm running into difficulty because the Numbers class doesn't really support what I want to do. What I've tried so far is this:

public class Summer<E extends Number> {


    public E sumValue(List<E> objectsToSum) {
        E total = (E) new Object();
        for (E number : objectsToSum){
            total += number;
        }
        return null;

    }

Obviously this will not work. How can I go about correcting this code so I could be given a list of <int> or <long> or whatever and return the sum?

like image 630
David M. Coe Avatar asked Dec 29 '11 15:12

David M. Coe


1 Answers

below method get numbers such as int, float, etc and calculate sum of them.

@SafeVarargs
private static <T extends Number> double sum(T... args) {
    double sum = 0d;
    for (T t : args) {
        sum += t.doubleValue();
    }
    return sum;
}
like image 133
Ali Mokhtare Avatar answered Sep 30 '22 18:09

Ali Mokhtare