๐ WAYPOINT LESSON
ArrayList mutation discipline
โญโญโญ advancedโณ 10 min read๐ Lesson 183 of 256
Backward loops, build-a-new-list, and the forbidden for-each removal โ plus the two-cursor merge drain phase.
ArrayList mutation discipline. Three legal strategies, one forbidden one:
- Reverse index loop (
for (int i = list.size() - 1; i >= 0; i--)): removals cannot affect not-yet-visited indexes. The safest remove-matches loop. - Build a new list: read the old, append survivors. Costs memory, never misindexes.
- Write-index over the same list via
setโ advanced, rarely needed on the exam.
Forbidden: removing from an ArrayList inside a for-each loop โ ConcurrentModificationException. (The AP subset does test this as a "why does this crash" MCQ.)
Two-cursor merge (interleave): advance whichever input still has elements, alternating. The drain phase โ one list already exhausted โ is the boundary the distractors encode: they drop the tail of the longer list.
โก Now practice
Ready to CodeArray lab: two passes, write indices, safe removalSix problems where the index discipline is the whole difficulty.
6 challenges ยท ยท ~60 min