Unit 4 Cycle 1 Day 13: ArrayList Traversal and Removal

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

ArrayList Traversal and Removal

Section 4.5 — ArrayList Algorithms

Key Concept

Removing elements from an ArrayList while traversing it requires careful index management. When you remove the element at index i, all subsequent elements shift left, so the element that was at i + 1 is now at i. If you increment i normally, you skip the shifted element. Two safe approaches: decrement i after removal (or do not increment), or traverse backward from the end. The AP exam frequently tests forward removal bugs as error-spotting questions.

Consider the following code segment.

ArrayList list = new ArrayList(); list.add(3); list.add(1); list.add(4); list.add(1); list.add(5); for (int i = list.size() - 1; i >= 0; i--) { if (list.get(i) < 3) { list.remove(i); } } System.out.println(list);

What is printed?

Answer: (A) [3, 4, 5]

Traversing backward: i=4(5, keep), i=3(1, remove), i=2(4, keep), i=1(1, remove), i=0(3, keep). Result: [3, 4, 5].

Why Not the Others?

(B) Both 1's are removed, not just one.

(C) Backward traversal correctly removes all matching elements.

(D) Backward traversal avoids the index-shifting problem. No error occurs.

Common Mistake

When removing from an ArrayList during traversal, go BACKWARD to avoid skipping elements. Forward traversal skips the element that shifts into the removed position.

AP Exam Tip

Removing while traversing: go backward (i = size()-1; i >= 0; i--). This is safer than forward traversal because removed elements do not affect unvisited indices.

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.