Unit 4 Cycle 2 Day 9: While Loop Removal Pattern

Unit 4 Advanced (Cycle 2) Day 9 of 28 Advanced

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.

ArrayList list = new ArrayList(); list.add("a"); list.add("b"); list.add("b"); list.add("c"); list.add("b"); int i = 0; while (i < list.size()) { if (list.get(i).equals("b")) list.remove(i); else i++; } System.out.println(list);

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.

Review this topic: Section 4.5 — ArrayList Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.