Question

I am trying to create a generic method that adds any list of numeric types in java. I would like to be able to use this method to add Integers, Doubles, Longs etc.. The below does not seem to work. I get compilation exceptions in eclipse saying: The operator + is undefined for the argument type(s) Number, T What could be the problemo? Thank you in advance.

public static <T extends Number> T sum(ArrayList<T> nums){
    Number retVal = 0.0;
    for (T val : nums){
        retVal = retVal+ val;
    }
    return (T) retVal;
}
Was it helpful?

Solution

Consider what the Java Language Specification says about the additive + operator

If the type of either operand of a + operator is String, then the operation is string concatenation.

Otherwise, the type of each of the operands of the + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.

Number is not a type that is convertible to a primitive. You therefore cannot use the + operator with variables of that type.

Consider using a different type or overloading your methods for each numeric type.

OTHER TIPS

instead of retVal = retVal+ val;

Use like below.

retVal = retVal.doubleValue()+ val.doubleValue();

Consider what you are asking for. You want a collection into which you can place numbers of arbitrary types, and perform operations like sum(). There are eight distinct number subtypes (BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short, not counting the atomic versions).

You will have noticed that java.lang.Number has no arithmetic methods, like add() or multiply(). You can't just go adding up instances of Number subclasses willy-nilly; you must consider each possible pairing, decide the rules for converting one or both to a common type for which addition is defined, and then decide what the result type is.

Then this has to be applied for each number you add to the running total. This is a non-trivial design task.

Luckily you can piggy-back off the design decisions already present for primitive types in the JLS, but it's still going to be a lot of work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top