Unit 4 Cycle 1 Day 13: ArrayList Traversal and Removal
Share
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.
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.