I know what is a fail-fast and fail-safe iterator. Fail-Fast iterators immediately throw ConcurrentModificationException if there is a structural modification of the collection.
Fail-Safe doesn't throw any exception as they work on a clone of collection.
My question is how does a fail-fast iterator come to know that a modification is made to my collection?
You can check the implementation yourself.
Let's consider
ArrayListas an example.It has an inner
Itrclass, which theiterator()method returns an instance of.The
Itrclass has anexpectedModCountcounter, which is initialized with the enclosingArrayList'smodCount:When you call methods of the
Iterator, such asnext()orremove(), it calls thecheckForComodification()method:which throws an exception if the
ArrayList'smodCounthas incremented since theIteratorinstance was created.