Iterators are basically used to traverse over a set of objects one by one. Java supports two types of Iterators
- Fail Fast Iterator
- Fail Safe Iterator
Fail Fast Iterator
Fail fast iterator do not allow any modifications to a collection while iterating/traversing the collection.By modification I mean any updating, addition of elements in the collection.If you try to modify the collection during iteration ,ConcurrentModificationException is thrown.
In the above code we are trying to add a new element in the map. The fail fast iterator throws ConcurrentModificationException if a new element is added while iterating the Collection.
Similarly, if you try to remove an element from the map (map.remove() method) while iterating the collection ,ConcurrentModificationException is thrown.
However, if you try to remove an element from the Collection while iterating it ( iterator.remove() method) , no exception is thrown.
Fail Safe Iterator
Fail safe iterator allow modifications to a collection while iterating the collection.You can do any updating, removal or addition in a collection while traversing the collection without any exceptions being thrown.The reason being the iteration is performed on the clone/copy of the collection not on the actual collection so the modification done of the actual collection go unnoticed by the Iterator.This means if the collection is modified while traversal you might see stale values during iteration .So,basically the iteration is weakly consistent.
I hope you enjoyed reading this article.Happy Coding 🙂