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

1k Views Asked by At
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.

2

There are 2 best solutions below

1
Eran On BEST ANSWER

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();
        }
    }
1
Peter Lawrey On

A key detail is that Java only has primitives and references.

When you add something to a List or any collection, it is a copy of the reference.

If you modify the object referenced, the collection is not modified though if you print the contents it might appear so.

If you call add or remove on a collection, for LinkedList and ArrayList, the iterator isn't modified but can no longer iterate (there is one exception)

If you use a CopyOnWriteArrayList you can modify the collection and keep iterating, however the iterator doesn't see the change.