Calculate average or take in an ArrayList as a parameter to a function

前端 未结 2 1663
野性不改
野性不改 2021-02-11 04:50

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

If not, can I make a function that will do that by taking in the name of the ArrayList and r

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-11 05:10

    It's really simple:

    // Better use a `List`. It is more generic and it also receives an `ArrayList`.
    public static double average(List 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;
    }
    

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

提交回复
热议问题