How Iterator works in java

Many times you will be asked this question in your interviews. e.g. How Iterator works in java, how it remove objects from List? While removing objects from list, when it may produce ConcurrentModificationException?

In Java, when you create an iterator, it starts to count the modifications that were applied on the collection. If the iterator detects that some modifications were made without using its method (or using another iterator on the same collection), it cannot guarantee anymore that it will not pass twice on the same element or skip one, so it throws this exception.

ArrayList methods always increase a counter ‘modCount‘ declared as:

protected transient int modCount = 0;

When you create an Iterator/ListIterator on arraylist, this modCount is used to initialize expectedModCount for that Iterator instance.

int expectedModCount = modCount;

Any operation done on ArrayList directly (without using iterator instance) will increase the modCount. Iterator’s all methods perform a check to validate the equality of modCount == expectedModCount – before performing the operation. If they do not match, it simply throws the exception.

final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

I hope above explanation will help you answer this interview question.

Happy Learning !!

Leave a Reply

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.