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
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:
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