Iterators is a very powerful programming construct. As the name implies, an iterate lets you iterate i.e. run over a list. The iterator can be used to perform various functions on the list.
However, when one thread is iterating over the list, if another thread tries to concurrently modify the underlying list, it results in ConcurrentModificationException. The following code snippets showcases the concept of ConcurrentModificationException.
If we try to add an element to the list while the list is being iterated, it can result in ConucurrentModificationException. There is an integer variable called ‘modCount’ which keeps track of the number of times the list size has been changed. This modCount is used in every next() call.
The ConcurrentModificationException can be avoided by locking the list.
Similarly, the for-each loops also use the Iterator in the background to iterate through the entire collection/ list. Since the for-each loop hides the iterator, it cannot be used to remove/ replace the items belonging to the list/ collection. Trying to remove/ replace the list using for-each loop also creates a ConcurrentModificationException.
Thanks — R