Unit 4 Cycle 1 Day 15: ArrayList: Forward Removal Bug

Unit 4 Foundation (Cycle 1) Day 15 of 28 Foundation

ArrayList: Forward Removal Bug

Section 4.5 — ArrayList Algorithms

Key Concept

The forward removal bug is the most commonly tested ArrayList error on the AP exam. When removing elements in a forward loop (for (int i = 0; i < list.size(); i++)), removing at index i shifts elements left, but i still increments, skipping the next element. For consecutive elements that should be removed, only every other one is actually removed. The fix is to either not increment i after a removal, decrement i after removal, or traverse backward.

Consider the following code segment intended to remove all "X" values.

ArrayList list = new ArrayList(); list.add("X"); list.add("X"); list.add("Y"); for (int i = 0; i < list.size(); i++) { if (list.get(i).equals("X")) { list.remove(i); } } System.out.println(list);

What is printed?

Answer: (B) [X, Y]

i=0: "X" removed. List becomes [X, Y]. i=1: "Y" checked (not X). The second "X" (now at index 0) was skipped because i moved to 1 after the removal.

Why Not the Others?

(A) Forward traversal misses the second "X" that shifted to index 0.

(C) Not all elements are removed. The second "X" is skipped.

(D) No exception occurs, but the logic is flawed.

Common Mistake

Forward removal bug: when you remove at index i, elements shift left. The next element moves to index i, but the loop increments to i+1, skipping it. Fix: traverse backward or decrement i after removal.

AP Exam Tip

This is a VERY common AP exam trap. Forward traversal + removal = skipped elements. Solutions: (1) traverse backward, (2) use i-- after remove, (3) use while loop.

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.