2 回答

TA貢獻2037條經驗 獲得超6個贊
你可以自己檢查一下實現情況。
讓我們考慮ArrayList一個例子。
它有一個內部Itr類,該iterator()方法返回該內部類的實例。
該類Itr有一個expectedModCount計數器,它是用封閉的ArrayList's初始化的modCount:
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;
...
}
當您調用 的方法Iterator(例如next()或 )時remove(),它會調用該checkForComodification()方法:
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
如果自創建實例以來ArrayList'modCount已遞增,則會引發異常。Iterator

TA貢獻1818條經驗 獲得超11個贊
沒有單一的方法可以實現這一點。
ArrayList
在(以及 中的其他類)的情況下java.util
,迭代器保留一個int expectedModCount
(“預期修改計數”),它與 的 (“修改計數”) 進行比較AbstractList
,int modCount
只要列表有結構修改,它就會更新;如果兩個值不同,迭代器將引發異常。
添加回答
舉報