javalinked-listiteratorlistiterator

Is iterator.next modified if the underlying list is modified with LinkedList add method?


intLinkList = 2, 4, 6, 8, 10
Iterator itr = intLinkList.iterator()

Say the iterator is iterating and currently pointing at Integer 6.

itr current item  = 6
itr previous item = 4
itr next item     = 8

When the itr is currently pointing at Integer 6, I use the Linklists' add(Object obj, int index) method to add/insert Integer 7 between Integer 6 and Integer 8.

I understand this itr instance is invalid after this modification because the underlying list has been modified, hence modCount != expectedModCount.

My question is this: Does the modification using LinkedList's add method change the item the itr.next is pointing at? I did some reading and I know this will throw a ConcurrentModificationException. But this does not answer my question if the itr.next item is modified if the underlying list get modified while iterator is iterating.


Solution

  • Does the modification using LinkedList's add method change the item the itr.next is pointing at?

    No.

    Calling LinkedList's add doesn't change anything in the Iterator's state. Once you call, the Iterator's next() method, and before the iterator calculates the next element to return, it will check for modification and throw the ConcurrentModificationException.

    Here's the relevant code, from AbstractList$Itr:

        public E next() {
            checkForComodification(); // will throw ConcurrentModificationException
                                      // before the Iterator's state is changed
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }