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 !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

3 thoughts on “How Iterator works in java”

  1. Hi Lokesh,

    “ArrayList methods always increase/decrease a counter ‘modCount‘ declared as:”
    I think it should be only increase, else please clarify.

    Thanks
    Anil

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.