Sum all the elements java arraylist

user2324946 picture user2324946 · Apr 26, 2013 · Viewed 217.4k times · Source

If I had: ArrayList<Double> m = new ArrayList<Double>(); with the double values ​​inside, how should I do to add up all the ArrayList elements?

public double incassoMargherita()
{
 double sum = 0;
 for(int i = 0; i < m.size(); i++)
 {          
 }
 return sum;
}

as?

Answer

Barranka picture Barranka · Apr 26, 2013

Two ways:

Use indexes:

double sum = 0;
for(int i = 0; i < m.size(); i++)
    sum += m.get(i);
return sum;

Use the "for each" style:

double sum = 0;
for(Double d : m)
    sum += d;
return sum;