计算平均值或将ArrayList作为函数的参数

Geo*_* K. 2 java average function arraylist

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

如果没有,我可以通过获取ArrayList的名称并返回其平均值来创建一个能够做到这一点的函数吗?

Ósc*_*pez 9

这很简单:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

为了获得更好的性能,请使用int[]而不是ArrayList<Integer>.

  • 这会溢出来. (2认同)