Is there a prevalent technique to sum the elements of an array having generic type but limited to Number?

Viewed 519

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?

1 Answers

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));
Related