对所有元素求和 java arraylist

2022-01-09 00:00:00 sum arraylist java

如果我有:ArrayList<Double>m = new ArrayList();里面有double值,怎么把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;
}

作为?

推荐答案

两种方式:

使用索引:

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

使用for each"样式:

Use the "for each" style:

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

相关文章