Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

Sum all the elements java arraylist

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?

question from:https://stackoverflow.com/questions/16242733/sum-all-the-elements-java-arraylist

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...