☕ Java Intermediate

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

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.