计算平均值或将 ArrayList 作为函数的参数 [英] Calculate average or take in an ArrayList as a parameter to a function
本文介绍了计算平均值或将 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
.
For even better performance, use int[]
instead of ArrayList<Integer>
.
这篇关于计算平均值或将 ArrayList 作为函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文