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-typeN
but then I can't initialize it with0
or even with theInteger
wrapper class'
N result = Integer.valueOf(0);
which I initially thought might be possible since theInteger
class extended theNumber
class. - Then I tried initializing it as
null
N result = null;
but then this line,
result = result + array[i].intValue();
throws an error statingOperator + cannot be applied to N, int
. I can't change the line to
result = result + array[i];
because then it showsOperator + 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?
Number
subclass in your implementation; so the benefits of using a generic parameter are lost anyway. Better choose one concrete subclass (likeDouble
orBigDecimal
) and make that the return type, and do calculations with that type.