Calculating average of an array list?

后端 未结 11 884
天涯浪人
天涯浪人 2020-11-29 09:04

I\'m trying to use the below code to calculate the average of a set of values that a user enters and display it in a jTextArea but it does not work properly. Sa

11条回答
  •  孤街浪徒
    2020-11-29 09:25

    Correct and fast way compute average for List:

    private double calculateAverage(List marks) {
        long sum = 0;
        for (Integer mark : marks) {
            sum += mark;
        }
        return marks.isEmpty()? 0: 1.0*sum/marks.size();
    }
    

    This solution take into account:

    • Handle overflow
    • Do not allocate memory like Java8 stream
    • Do not use slow BigDecimal

    It works coorectly for List, because any list contains less that 2^31 int, and it is possible to use long as accumulator.

    PS

    Actually foreach allocate memory - you should use old style for() cycle in mission critical parts

提交回复
热议问题