Unit 4 Day 17 Arraylist Remove Traversal
Share
Practice Question
// Segment I
ArrayList<Integer> nums = new ArrayList<>();
nums.add(2); nums.add(4); nums.add(6); nums.add(8);
for (int k = 0; k < nums.size(); k++)
{
if (nums.get(k) % 2 == 0)
nums.remove(k);
}
// Segment II
ArrayList<Integer> nums = new ArrayList<>();
nums.add(2); nums.add(4); nums.add(6); nums.add(8);
for (int k = nums.size() - 1; k >= 0; k--)
{
if (nums.get(k) % 2 == 0)
nums.remove(k);
}
// Segment III
ArrayList<Integer> nums = new ArrayList<>();
nums.add(2); nums.add(4); nums.add(6); nums.add(8);
for (Integer val : nums)
{
if (val % 2 == 0)
nums.remove(val);
}
Step-by-Step Trace
// Segment I - FAILS (skips elements)
// Initial: [2, 4, 6, 8], size=4
// k=0: remove 2, list becomes [4, 6, 8], size=3
// k=1: check index 1, that is 6 (4 was skipped!), remove 6
// k=2: k >= size(2), loop ends
// Result: [4, 8] - NOT empty!
// Segment II - WORKS (backward traversal)
// k=3: remove 8, list becomes [2, 4, 6]
// k=2: remove 6, list becomes [2, 4]
// k=1: remove 4, list becomes [2]
// k=0: remove 2, list becomes []
// Result: [] - correctly empty!
// Segment III - THROWS EXCEPTION
// Enhanced for-loop cannot modify list during iteration
// ConcurrentModificationException at runtime
Key Concept
Why backward traversal works: When you remove an element, all elements after it shift left. If you traverse backward, the shifted elements are ones you have already processed, so nothing gets skipped.
Why forward traversal fails: After removing index k, the element that was at k+1 shifts to k. When k increments, you skip that shifted element.
Why enhanced for-loop fails: Java iterators detect structural modification and throw ConcurrentModificationException to prevent unpredictable behavior.
Common Mistakes
When removing during forward traversal, elements shift left but the index keeps incrementing. This causes every other element to be skipped. Trace through carefully!
You CANNOT modify an ArrayList while iterating with for-each. Java throws ConcurrentModificationException at runtime. This is a common AP exam trap.
When removing elements during traversal, ALWAYS use backward iteration (from size-1 down to 0) or use an Iterator with its remove() method. Never modify an ArrayList inside an enhanced for-loop.
Want More Practice?
Master AP CSA with guided practice and expert help
Schedule 1-on-1 Tutoring Practice FRQs