I was asked to implement the following method:
public static double sum(ArrayList<Integer> list)
So I came up with:
public static double sum(ArrayList<Integer> list)
{
int sum = 0;
for (Integer element : list)
{
sum += element;
}
return sum;
}
Now I'm asked to refactor the method so that its argument can be an ArrayList
of any numeric type. I tried:
public static <T> double sum(ArrayList<T> list)
{
double sum = 0;
for (T element : list)
{
sum += element;
}
return sum;
}
But this doesn't work because +
is not defined for generic type T
. I also tried N
in place of T
but still got the same error. Any hints?