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?
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;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With