๐ WAYPOINT LESSON
Integers in lists
โญโญ intermediateโณ 12 min read๐ Lesson 106 of 256
Autoboxing, == vs equals between Integers, and object collections.
ArrayLists hold objects, so ArrayList<Integer> stores Integer boxes โ
and arithmetic quietly unboxes them:
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(7);
int x = nums.get(0) + 1; // unboxes to int, x = 8
Integer boxed = nums.get(0);
if (boxed == 7) { ... } // true: unboxing comparison
if (nums.get(0) == new Integer(7)) { ... } // int comparison, true
But between two Integers, == compares references:
Integer a = 200, b = 200;
if (a == b) { } // false outside the small-value cache!
if (a.equals(b)) { } // true โ always compare objects with equals
(The small-value cache makes -128..127 sometimes compare equal with
== โ a trap that only looks reliable in tests.)
The exam's ArrayList FRQ always wraps a real class:
ArrayList<Member> roster = new ArrayList<Member>();
for (Member m : roster) {
if (m.getPoints() >= threshold) { count++; }
}
For-each is perfect for reading; the moment you must remove,
switch to an indexed loop. And the length-vs-size discipline:
arrays use .length (no parens), Strings use .length(),
ArrayLists use .size().
โก Now practice
Ready to CodeArrayList labBackward removal and insertion, value semantics, halves swap, object totals.
5 challenges ยท ยท ~60 min