1

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

3
  • 1
    What's your error? Also, show how you define grades. Commented Feb 23, 2014 at 18:25
  • Okay, I'm glad you showed us your error. Now, is T declared at the class level? How do you instantiate the instance of this object? Commented Feb 23, 2014 at 18:29
  • @Makoto I guess that information doesn't really matter here. Clearly we can't use + operator with type T. Commented Feb 23, 2014 at 18:31

1 Answer 1

8

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.