Skip to the page

Java collections · Write code

Removing items inside a for-each loop

The interviewer asks

This code removes expired orders from a list. Sometimes it throws, and sometimes it silently leaves an expired order in the list. Why? How do you fix it?

List<Order> orders = new ArrayList<>(repository.findPending());
for (Order o : orders) {
    if (o.isExpired()) {
        orders.remove(o);
    }
}

Then

Follow-ups the interviewer asks next

  1. Why does removing the second-to-last element not throw?
  2. Would CopyOnWriteArrayList fix it? What does it cost?
  3. Can you get ConcurrentModificationException with only one thread?
  4. What happens with an index loop that calls remove(i) and then i++?

The answer

What a strong answer covers

  • for-each uses an Iterator. orders.remove(o) changes the list's modification count; the iterator's next() notices and throws ConcurrentModificationException. One thread is enough.
  • Edge case: after removing the second-to-last element, hasNext() sees the cursor equal to the new size and returns false, so the loop ends quietly and the last element is never checked.
  • The check is best-effort, not a guarantee.
  • Fixes: orders.removeIf(Order::isExpired); an explicit Iterator with it.remove(); build a new list with a stream filter; or filter in the query.
  • Fail-fast (ArrayList, HashMap iterators) versus snapshot (CopyOnWriteArrayList: every write copies the array, good for rarely changing lists such as listeners) and weakly consistent (ConcurrentHashMap).
  • An index loop with remove(i) skips the element that moves into position i.

The red pen

Common traps

Avoid:"it only happens with multiple threads"; wrapping the loop in try-catch.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview