3

I created a generic-type array bounded with Number. I created a method to sum all of its elements.
Here is the code

class GenericMethod {
    public static void main(String[] args) {
        Integer[] arr = {10, 20, 30, 40, 50};
        int sum = GenericMethod.<Integer>sumOfAllElements(arr);
        System.out.println(sum);
        Float[] floats = {3.0f, 4.19f};
        int sum2 = GenericMethod.<Float>sum(floats);
        System.out.println(sum2);
    }

    public static <T extends Number> int sumOfAllElements(T[] arr) {
        int response = 0;
        for (T t : arr) {
            response += t.intValue();
        }
        return response;
    }
}

In the method, the return type is still an int. I would like to change the return-type to a generic as well.

  • I've tried declaring the response variable with the generic-type N but then I can't initialize it with 0 or even with the Integer wrapper class'
    N result = Integer.valueOf(0);
    which I initially thought might be possible since the Integer class extended the Number class.
  • Then I tried initializing it as null
    N result = null;
    but then this line,
    result = result + array[i].intValue();
    throws an error stating Operator + cannot be applied to N, int. I can't change the line to
    result = result + array[i];
    because then it shows Operator + cannot be applied to N, N.
  • I've also tried this "hack"
public static <N extends Number> N sum(N[] array) {
        Number result = array[0];
        if (result instanceof Integer) {
            Integer temp = result.intValue();
            for (int i = 0; i < array.length; i++) {
                temp += array[i].intValue();
            }
            result = temp;
        }
        return (N) result;
    }

but then I would have to specify the cases for all Number types.
Could someone please help me with, - modifying this method, so that it could return a generic-type instead of int. - help me understand the nature and cause of this problem, is it because the class is still a non-generic type?

2
  • Are you ok with passing in additional arguments?
    – daniu
    Oct 15, 2019 at 8:17
  • You wouldn't be able to perform arithmetic operations without using a concrete Number subclass in your implementation; so the benefits of using a generic parameter are lost anyway. Better choose one concrete subclass (like Double or BigDecimal) and make that the return type, and do calculations with that type.
    – ernest_k
    Oct 15, 2019 at 8:20

1 Answer 1

4

The simplest method, if using Java 8+, would be to use Arrays.stream(T[]) to create a stream of T(s) and then reduce that stream with addition. Like,

Integer[] arr = { 10, 20, 30, 40, 50 };
Float[] floats = { 3.0f, 4.19f };
System.out.println(Arrays.stream(arr).reduce((a, b) -> a + b));
System.out.println(Arrays.stream(floats).reduce((a, b) -> a + b));

No additional methods required. But, if you want to make that a method, you could pass the operation like

public static <T> T add(T[] arr, BinaryOperator<T> op) {
    return Arrays.stream(arr).reduce(op).get();
}

and then call it like

System.out.println(add(arr, (a, b) -> a + b));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.