Totals, Counts, and Extremes in an ArrayList
Unboxing in a total
A grocery receipt is stored as
ArrayList<Double> prices, holding 2.49, 5.00, 1.25, and 3.75.double total = 0.0;
for (double p : prices)
{
total += p;
}
Each element is a
Double, unboxed into the double variable p as the loop hands it over. The loop adds the four prices, so total ends at 12.49. Over a double[] this loop would be unchanged. An indexed version uses size() and get(i) where an array uses length and brackets.A count over 3.00
int over = 0;
for (double p : prices)
{
if (p > 3.00)
{
over++;
}
}
Only the 5.00 and the 3.75 pass the test, so
over is 2.For the average price,
total / prices.size() divides a double by an int, so it keeps the fraction and gives 3.1225.The cheapest item, by index
double cheapest = prices.get(0);
for (int i = 1; i < prices.size(); i++)
{
if (prices.get(i) < cheapest)
{
cheapest = prices.get(i);
}
}
Each
prices.get(i) returns a Double, which is unboxed for the comparison with cheapest. The 1.25 replaces the 2.49, and nothing later is smaller, so cheapest ends at 1.25. The seed prices.get(0) needs a list that isn't empty. On an empty list, get(0) throws an IndexOutOfBoundsException.