Java:深入了解ArrayList.iterator()

iterator通常会引起问题,因为开发人员经常不知道它是如何工作的。以下代码来自的源代码ArrayList。

一个常见的问题是抛出java.util.ConcurrentModificationException。该异常实际上是在remove方法中引发的。remove()必须被称为next()。如果remove()在之前被调用next(),modCount != expectedModCount则满足并满足条件的条件会更改arraylist的大小,并引发ConcurrentModificationException。

 
...
 
public Iterator<E> iterator() {
    return new Itr();
}
 
/**
 * An optimized version of AbstractList.Itr
 */
private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;
 
    public boolean hasNext() {
        return cursor != size;
    }
 
    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];
    }
 
    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();
 
        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }
 
    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}
 
...

在这里插入图片描述

发布了17 篇原创文章 · 获赞 0 · 访问量 184

猜你喜欢

转载自blog.csdn.net/qq_41806546/article/details/105133918
今日推荐