是否有内置方法来计算整数 ArrayList 的平均值?
如果没有,我可以创建一个函数,通过获取 ArrayList 的名称并返回其平均值来实现此目的吗?
这真的很简单:
// 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<Integer>
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)