AP CSA Arraylist Remove While Iterating

ArrayList Remove While Iterating in AP CSA: Complete Guide (2025-2026)

Removing elements from an ArrayList while iterating in AP CSA is the single most commonly missed FRQ pattern in Unit 4 (30–40%). When you remove an element during a forward loop, the remaining elements shift left by one position — and your loop index advances past the element that just moved into the removed element's slot, silently skipping it. The AP exam tests this pattern almost every year, and the fix (iterating backwards or adjusting the index) must become second nature.

💻 Code Examples — Predict First

Before running each example, write down your prediction. This is the single most effective AP exam study technique.

🤔 Predict the output before running:

Example 1: The Buggy Version (Skips Elements)
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList nums = new ArrayList();
        nums.add(1); nums.add(2); nums.add(3); nums.add(4); nums.add(5);
        // BUGGY: removes evens but skips some
        for (int i = 0; i < nums.size(); i++) {
            if (nums.get(i) % 2 == 0) {
                nums.remove(i);
            }
        }
        System.out.println(nums);
    }
}
Running…

[1, 3, 5]? Actually prints [1, 3, 4] — When 2 is removed at index 1, the value 3 shifts to index 1. But i advances to 2, skipping 3. Then 4 at index 2 is removed. But 3 was never checked after shifting. This is the skip-on-remove bug.

🤔 Predict the output before running:

Example 2: Correct Fix — Traverse Backwards
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList nums = new ArrayList();
        nums.add(1); nums.add(2); nums.add(3); nums.add(4); nums.add(5);
        // CORRECT: traverse backwards
        for (int i = nums.size() - 1; i >= 0; i--) {
            if (nums.get(i) % 2 == 0) {
                nums.remove(i);
            }
        }
        System.out.println(nums);
    }
}
Running…

[1, 3, 5] — Traversing backwards means removals don't affect unprocessed elements (they are all to the LEFT of the current index). This is the cleanest fix and the AP exam's preferred solution.

🤔 Predict the output before running:

Example 3: Correct Fix — Decrement After Remove
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList nums = new ArrayList();
        nums.add(1); nums.add(2); nums.add(3); nums.add(4); nums.add(5);
        // ALSO CORRECT: decrement index after remove
        for (int i = 0; i < nums.size(); i++) {
            if (nums.get(i) % 2 == 0) {
                nums.remove(i);
                i--;  // re-examine the shifted element
            }
        }
        System.out.println(nums);
    }
}
Running…

[1, 3, 5] — After removing at index i, decrement i so the loop re-examines the element that shifted into position i. Both this and the backwards traversal are valid AP exam solutions.

❌ Common Pitfalls

These are the mistakes students most often make on the AP CSA exam with ArrayList remove while iterating AP CSA. Study them carefully.

1
⚠ Forgetting that remove() shifts all subsequent elements left

When you remove element at index i, elements i+1, i+2, ... all move down by 1. The new element at index i is what was previously at index i+1. A forward loop that doesn't account for this will skip checking the shifted element.

// After remove(1) on [A,B,C,D]:
// List becomes [A,C,D]
// If i was 1 and advances to 2, C is NEVER checked
2
⚠ Using enhanced for loop to remove elements

The enhanced for loop throws ConcurrentModificationException when you call list.remove() inside it. Always use a standard indexed for loop when removing elements.

for (int v : list) {
    if (v < 0) {
        list.remove(Integer.valueOf(v)); // EXCEPTION!
    }
}
3
⚠ Removing by value instead of by index accidentally

In an ArrayList, remove(2) removes at INDEX 2. To remove the VALUE 2, use remove(Integer.valueOf(2)). The AP exam may ask you to remove a specific value, and the two forms behave completely differently.

4
⚠ Not adjusting size() check after removes

After removing elements, size() decreases. A forward loop that doesn't compensate (via i-- or backwards traversal) may terminate too early or skip elements.

🎓 AP Exam Tip

The AP CSA FRQ rubric almost always includes a point for correctly handling the remove-while-iterating case. When you write a remove method, write the backwards loop first: 'for (int i = list.size()-1; i >= 0; i--)'. This approach is always correct and graders recognize it immediately.

⚠ Watch Out!

Memorize this backwards remove template: for (int i = list.size()-1; i >= 0; i--) { if (condition) list.remove(i); } — It works for any remove condition, never skips elements, and earns full credit on AP FRQs.

✍ Check for Understanding (8 Questions)

Your Score: 0 / 0
1. Why does a forward loop skip elements when removing from an ArrayList?
2. What is the correct direction to traverse when removing elements from an ArrayList?
3. What does this buggy code actually print?
// list = [2,4,6]
for(int i=0;i if(list.get(i)%2==0) list.remove(i);
4. Which of the following correctly removes all negative values from an ArrayList?
5. What exception does this code throw?
for(Integer v : list) if(v>10) list.remove(v);
6. After removing at index 2 from [10,20,30,40,50], what is list.get(2)?
7. The forward loop with i-- after remove produces the same result as backwards traversal. When is backwards traversal PREFERRED?
8. Which code segment correctly removes the first occurrence of value 5 from ArrayList list?

❓ Frequently Asked Questions

Why can't I remove elements during an enhanced for loop?

The enhanced for loop uses an iterator internally. When you modify the ArrayList's structure (add or remove) during iteration, the iterator detects the modification and throws ConcurrentModificationException.

What is the backwards traversal pattern for removing from an ArrayList?

for (int i = list.size()-1; i >= 0; i--) { if (condition) list.remove(i); }. Starting from the end ensures that removals only affect indices you have already processed (higher indices), not the ones you still need to check.

What is the skip-on-remove bug?

The skip-on-remove bug occurs in a forward loop when you remove element at index i. The element previously at i+1 shifts to i, but the loop increments i to i+1, skipping the shifted element. This causes the loop to miss checking elements that moved.

How do I remove a specific VALUE from an ArrayList?

Use remove(Integer.valueOf(value)) to remove by value, or loop and find the index first. remove(int index) removes by position, not by value. For example, list.remove(3) removes at index 3, not the value 3.

Should I use backwards traversal or i-- after remove?

Both approaches produce correct results. Backwards traversal is generally preferred on AP FRQs because it is simpler and less prone to errors. The i-- approach works but requires careful implementation to avoid off-by-one errors.

TC

Tanner Crow — AP CS Teacher & Tutor

11+ years teaching AP Computer Science at Blue Valley North High School (Overland Park, KS). Verified Wyzant tutor with 1,845+ hours, 451+ five-star reviews, and a 5.0 rating. His AP CSA students score 5s at more than double the national rate.

  • 54.5% of students score 5 on AP CSA (national avg: 25.5%)
  • 1,845+ verified tutoring hours • 5.0 rating
  • Free 1-on-1 tutoring inquiry: Wyzant Profile

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

tanner@apcsexamprep.com

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at tanner@apcsexamprep.com