Reputation: 133
I have an array list of generic types and i'm trying to create a method to calculate the average, but I cannot add the a generic without casting it first but I'm suppose to pass in integers or double how can i do this?
private ArrayList<T> grades;
public double computeAverage()
{
double average = 0;
double sum = 0;
for (int i = 0; i < grades.size(); i++) {
sum = sum + grades.get(i); <<< ERROR
}
average = sum/grades.size();
return average;
}
Error: The operator + is undefined for the argument type(s) double, T
Upvotes: 1
Views: 89
Reputation: 11454
Still, after your edit, its unclear what T
is. If you're able to narrow it down to a Number
(which is the super class for Integer
and Double
as you mentioned), the following will work:
List<Number> numbers = new ArrayList<Number>();
for (Number number : numbers) {
sum += number.doubleValue();
}
Upvotes: 8