W.Cameron
W.Cameron

Reputation: 124

Why can I add a item into collection by iterator?

I am reading the code of AbstractList where there is a nest class Itr, and it's fine. What confuses me is why Java provide a set of methods to it's Iterator so that it can be used to modify the underlaying collection, such as add(),remove(),set().

What is the essential reason that You Must expose the collection to Iterator? Does it more convenient than modifing a collection by Collection's methods?

private class Itr implements Iterator<E> {

    //......bha

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            AbstractList.this.remove(lastRet);
            if (lastRet < cursor)
                cursor--;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException e) {
            throw new ConcurrentModificationException();
        }
    }
}

  private class ListItr extends Itr implements ListIterator<E> {
    ListItr(int index) {
        cursor = index;
    }
    public void set(E e) ///...
   public void add(E e) //.....

Upvotes: 2

Views: 79

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

If you directly modify a collection while it's being iterated, you may well get a ConcurrentModificationException because the iterator may become invalid. But if you do it via the iterator, then the iterator's implementation can ensure that it (the iterator) remains valid after the modification.

The iterator code can't do that if it doesn't know about the modification, though, which is why you do it through the iterator rather than directly.

While it would be possible to design collections and iterators such that modifying the collection directly would ensure it kept all iterators up-to-date, it's much more complex and the JDK designers didn't go that route.

Upvotes: 5

Related Questions