☕ 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.
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?