平均计算,或者在一个ArrayList作为参数传递给函数 [英] Calculate average or take in an ArrayList as a parameter to a function

查看:801
本文介绍了平均计算,或者在一个ArrayList作为参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个内置的方法来计算的整数ArrayList的平均

Is there a built-in method to calculate the average of an integer ArrayList?

如果没有,我可以做一个功能,将做到这一点,采取ArrayList中的名称,并返回其平均值?

If not, can I make a function that will do that by taking in the name of the ArrayList and returning its average value?

推荐答案

这真的很简单:

// Better use a `List`. It is more generic and it also receives an `ArrayList`.
public static double average(List<Integer> list) {
    // 'average' is undefined if there are no elements in the list.
    if (list == null || list.isEmpty())
        return 0.0;
    // Calculate the summation of the elements in the list
    long sum = 0;
    int n = list.size();
    // Iterating manually is faster than using an enhanced for loop.
    for (int i = 0; i < n; i++)
        sum += list.get(i);
    // We don't want to perform an integer division, so the cast is mandatory.
    return ((double) sum) / n;
}

有关更好的性能,使用 INT [] 而不是的ArrayList&LT;整数方式&gt;

For even better performance, use int[] instead of ArrayList<Integer>.

这篇关于平均计算,或者在一个ArrayList作为参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆