☕ Java Intermediate

What is the difference between fail-fast and fail-safe iterators?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

A fail-fast iterator immediately throws ConcurrentModificationException if the collection is structurally modified (elements added or removed) after the iterator was created — except through the iterator's own remove() method. Most Java collection iterators (ArrayList, HashMap, etc.) are fail-fast. They detect modification using an internal modCount. A fail-safe iterator works on a snapshot or copy of the collection and does not throw exceptions if the original is modified. Iterators for ConcurrentHashMap and CopyOnWriteArrayList are fail-safe. The tradeoff: fail-safe iterators may not reflect the latest state of the collection.

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last Java project, I used this when...' immediately makes your answer more credible and memorable.