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 Number
s 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.
]
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;
}