I have the following method:
private <E extends Number> double GetAverage(ArrayList<E> al)
{
double total = 0;
Iterator<E> itr = al.iterator();
while(itr.hasNext())
{
total += itr.next();
}
return total;
}
but it does not compile. I get a
“total cannot be resolved or is not a field”
on line
“total += itr.next();”
I understand that Java doesn’t know the value of E, but I hope you understand what I mean, what is the best way to create a generic method that adds the total(Numeric values) of an ArrayList.
There’s actually syntax errors with your code, you have line that’s not complete. Your full code should be:
Note: the return of ‘total’ and not undefined retVal