0

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?

yroc
  • 886
  • 1
  • 10
  • 16
  • If I could leave an answer, I would, but I can't. If you look at the duplicate question, I will leave an answer for it that has not been suggested. This may be a solution to the problem (potentially). – astrogeek14 Jun 23 '16 at 18:38
  • @astrogeek14 Thank you. I'll look out for your answer. – yroc Jun 23 '16 at 18:50
  • I have the answer posted. I hope it helps! – astrogeek14 Jun 23 '16 at 19:20
  • Much appreciated :-) I'll take some time to work through it. – yroc Jun 23 '16 at 19:30
  • `+` isn't defined for any reference type except `String`, so that is not surprising. Substituting a different variable name will not alter the semantics of the statement, naturally. – Lew Bloch Jun 23 '16 at 20:31

0 Answers0