Search code examples
javagenericsgeneric-collections

Generic Method not adding arbitrary Number types in java


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;
}

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.