College Board Unit 4
How it works
Because generics require class types, numeric ArrayLists store Integer and Double objects rather than int and double. Java autoboxes primitives into wrappers on the way in and unboxes them on the way out, so list.add(5) and int x = list.get(0); both compile. The values still behave like objects, which matters for comparison and for method overload resolution.
Compare wrapper values with equals rather than the equality operator.
Common error
Comparing two wrapper objects with the equality operator, which compares references and can be false for equal values.
Worked example
Java
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(7);
int value = list.get(0);
System.out.println(value + 2);Output
9Adding boxes 7 into an Integer; assigning get(0) to an int unboxes it.
Exercises
6.4.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
Integer a = 150;
Integer b = 150;
System.out.println(a.equals(b));
System.out.println(a.intValue() == b.intValue());Show solution
Output
true
trueequals compares the Integer values; explicitly unboxed primitive values also compare numerically.
6.4.2 · Write code
Write public static double mean(ArrayList<Integer> values). Assume a nonempty list of non-null values. Return an average that preserves the fractional part.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
public static double mean(ArrayList<Integer> values) {
int sum = 0;
for (int value : values) sum += value;
return (double) sum / values.size();
}Check your code
Java
System.out.println(mean(new ArrayList<Integer>(Arrays.asList(2,3))));
System.out.println(mean(new ArrayList<Integer>(Arrays.asList(-4))));Expected output
2.5
-4.0