**foreach刪除元素報錯java.util.ConcurrentModificationException**
private static void removeList(){
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(i);
}
for (Integer string : list) { //刪除報錯
list.remove(string);
}
}
list修改會記錄修改的次數, 在ArrayList和Itr內部內中都有記錄
ArrayList modCount
Itr expectedModCount Itr是 ArrayList的內部類,實現了迭代器
每次修改modCout都會+1,調用迭代器的remove(),
第一步: ArrayList.this.remove(lastRet);會先去刪除, modCount+1
第二步: 後面設置expectedModCount = modCount;
foreach遍歷實際就是 調用Itr迭代器遍歷,
Itr.next() 會調用checkForComodification()方法, 如果用list的remove(obj)方法, modCount被修改了
, 但是Itr迭代器中的expectedModCount沒有變。 在Itr.next()中校驗失敗
private class Itr implements Iterator<E> {
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();
}
}
public E next() {
checkForComodification();
...
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
foreach循環刪除報錯,可查看: https://blog.csdn.net/m0_37372711/article/details/54613741