0

If I have two Object implement Number Interface, is it possible to add them together?

public static <T extends Number> T[] prefixSum(T [] arr,T zero){
    int n = arr.length;
    T [] arr2 = (T[]) new Object [n+1];
    arr2[0] = zero;
    for (int i=0;i<n;i++){
        arr2[i+1] = arr[i] + arr2[i]; // ERROR
    }
    return arr2;
}

I got error message at line 6. How can I write this program generically?

worldterminator
  • 2,968
  • 6
  • 33
  • 52
  • You can't do that. First you can't have generic arrays. And to add the numbers, you have to unbox the primitives... and to not lose precision, you'd have to use ugly `instanceof` checks. So, I'd say, look for a different solution. – vanza Sep 26 '14 at 02:21
  • 1
    Related: [How to add two java.lang.Numbers?](http://stackoverflow.com/questions/2721390/how-to-add-two-java-lang-numbers) – Pang Sep 26 '14 at 02:23
  • @vanza You are wrong of course he can have generic arrays! – sotcha Sep 26 '14 at 02:55
  • @sotcha, true, I meant can't create generic arrays. The compiler will yell at you (and in the case of his code, spit out a warning). – vanza Sep 26 '14 at 04:23

1 Answers1

2

A few ground rules before we begin:

  • Arrays and generics simply don't mix well. You get into a lot of headaches about the ability to store data correctly inside of the array at runtime (i.e. ArrayStoreException), and a lot of raw types floating around (your compiler may have emitted a warning about the generic array creation you have up there).

    For that reason, we're going to move to List. It's generic and a lot more flexible. If you really want, you can convert it back.

  • Generics aren't really necessary here. You've got an array of Numbers coming in, with a Number as your zero value. Since any class that extends Number is-a Number, there's no harm in bringing them in. Conversely, it would bring us much unnecessary headache to bring a generic type in.

  • Thinking about it logically, the object hierarchy of Number is such that everything that could be considered a Number is capable of being Comparable as well (and luckily we don't need that). But, considering this chart of number types, I don't see any reason to utilize generics.

enter image description here]

Here's an example of how the code would look without generics, and only with Number. Mind, this is only taking the intValue, so all of your numbers will be integer-precise. If you want the float or double value, then that's possible too.

public static List<? extends Number> prefixSum(Number [] arr, Number zero){
    final List<Number> result = new ArrayList<Number>();
    result.add(zero);
    for(int i = 0; i < arr.length; i++) {
        final Number sum = arr[i].intValue() + result.get(i).intValue();
        result.add(sum);
    }
    return result;
}
Community
  • 1
  • 1
Makoto
  • 104,088
  • 27
  • 192
  • 230