Unit 4 Cycle 2 Day 9: While Loop Removal Pattern
Share
While Loop Removal Pattern
Section 4.5 — ArrayList Algorithms
Key Concept
The while loop removal pattern safely removes elements from an ArrayList by using a while loop with an explicit index that only increments when no removal occurs. When an element is removed, the index stays the same because the next element shifts into the current position. This pattern correctly handles consecutive elements that should be removed, unlike the buggy forward for loop approach. The AP exam compares this correct pattern against the buggy version.
Consider the following code segment.
What is printed?
Answer: (A) [a, c]
While loop only increments when NOT removing. All three "b"'s are removed correctly: [a, c].
Why Not the Others?
(B) All three "b" elements are removed.
(C) The while loop handles consecutive removals correctly.
(D) No error. The while-loop approach is safe.
Common Mistake
The while loop with conditional increment: only advance i when no removal occurs. After removal, re-check the same index since a new element shifted in.
AP Exam Tip
Three safe removal patterns: (1) backward for, (2) while + conditional increment, (3) build new list. All valid for AP exam.