是什么导致了 ConcurrentModificationException

What leads to ConcurrentModificationException

我正在阅读有关 ConcurrentModificationException 的信息。我为 iterator.Can 找到了这段代码,任何人都可以解释是什么导致了这个 exception.I 只是想为下面写的逻辑提供一些理由。

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();
    }
}

当您迭代它们时,您的基础元素数量正在改变大小,因此抛出异常。

请注意,这里的尝试并不是要从不可能的情况中恢复过来,而是要 "Fail" 尽可能早、干净地恢复。不抛出异常并使某些东西工作可能很容易,但行为是未定义的。这是尽一切可能确保您的迭代器中没有编码错误,而不仅仅是从不可能的代码角落恢复。

// This line is getting the underlying array out from "this" ArrayList   
Object[] elementData = ArrayList.this.elementData; 

// I is the current value of your cursor.  Every time you call "next"
// this cursor is being incremented to get the next value
// This statement is asking if your current cursor extends beyond the
// end of the array, if it does then "Something" happened to make the array
// smaller while we weren't looking...
if (i >= elementData.length) 
    // To indicate that the elementData array has changed size outside of
    // our current iterator, throw an exception to the user.
    throw new ConcurrentModificationException();

因此,要实现这一点,您需要创建一个迭代器,然后减小数组列表的大小,然后调用 "Next"。这应该给你一个 CME