Fail-Fast in HashMap and Other Collections
What you'll learn: You'll discover how fail-fast behavior extends beyond ArrayList to HashMap, HashSet, and nearly all standard Java collections.
The Big Picture
Just like ArrayList uses a modCount field to detect concurrent modifications, most Java collections implement fail-fast iterators. HashMap, HashSet, LinkedHashMap, TreeMap, TreeSet, and LinkedHashSet all throw ConcurrentModificationException if you modify the collection structure during iteration (except through the iterator's own remove() method).
How It Works Across Collections
Every fail-fast collection tracks modifications internally. When you call put(), remove(), or clear() on a HashMap, for example, its internal modification counter changes. The iterator checks this counter with each call to hasNext() or next(). If it detects a mismatch, it immediately throws ConcurrentModificationException.
This applies to:
- HashMap/HashSet: Adding or removing keys/elements
- TreeMap/TreeSet: Adding or removing entries
- LinkedHashMap/LinkedHashSet: Any structural modification
The Safe Pattern
The solution remains the same across all collections: use the iterator's own remove() method:
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 75);
Iterator<Map.Entry<String, Integer>> it = scores.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> entry = it.next();
if (entry.getValue() < 80) {
it.remove(); // Safe removal
}
}
This works because the iterator coordinates with the collection's modification tracker.
Key Takeaway: Fail-fast behavior protects you from modification bugs in nearly all standard Java collections—HashMap, HashSet, TreeMap, TreeSet, and their variants—by immediately throwing exceptions when structural changes occur during iteration, unless you use the iterator's remove() method.