0

I want to recursively sum all generic elements in an array an the problem I'm facing is during the final return statement I can not use the + operator or any method because its not defined for the type given here is my code:

public static <T extends Number> T binarySum(T[] arr, int low , int high) {
    if(low > high) return null;
    else if(low == high) return arr[low];
    else {
       int mid = (low + high) / 2;
       return binarySum(arr, low, high) + binarySum(arr, mid + 1, high);
    }
}
  • 1
    If the `+` operator was defined for `T extends Number`, what type would it return? – Sam Sep 06 '22 at 13:38
  • 2
    The recursion and generics is just a red herring. You really want to ask how to sum 2 instances of Number. Take a look at this question https://stackoverflow.com/questions/2721390/how-to-add-two-java-lang-numbers – bhspencer Sep 06 '22 at 13:39
  • Also: rather than returning `null` in the `low > high` case, you want to return "zero" (by which I mean, `Integer.valueOf(0)` or `Double.valueOf(0)` or whatever to match the `T`). If you return `null`, you will potentially attempt to add `null` to something, when actually the sum of no things is zero. – Andy Turner Sep 06 '22 at 13:52
  • Also: you have a typo in `binarySum(arr, low, high)`. – Andy Turner Sep 06 '22 at 14:54

0 Answers0