Sum all the elements java arraylist

后端 未结 5 855
醉话见心
醉话见心 2020-11-27 05:21

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

5条回答
  •  失恋的感觉
    2020-11-27 06:23

    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;
    

提交回复
热议问题