标签:util 初始 ORC class 允许 one 子类 博客 遍历
注:参考博客:https://www.cnblogs.com/dolphin0520/p/3933551.html
1、单线程环境下的异常重现
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(2);
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()){
Integer integer = iterator.next();
if(integer==2) {
list.remove(integer);
//iterator.remove(); //正确写法
}
}
}
在while(iterator.hasNext()) 循环遍历时,只允许删除ArrayList 内部的 elementData[ ] 的最后一个元素,而不允许从中间删除。
在 iterator.next() 的源码中,会首先执行方法:checkForComodification(); 该方法:
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
只有当两个变量值相等时才不会报错。而 list.add(2)操作和 list.remove(integer); 操作会使 modCount++; 但是变量 expectedModCount 是内部类的 Itr 子类 的 变量,该子类的实例化方法是:list.iterator(); 实例对象时赋初始值:
int expectedModCount = modCount; 所以,不允许在 while(iterator.hasNext()) 循环方法内 有list.add(2)操作和 list.remove(integer);操作,否则会导致expectedModCount != modCount ,进而导致 throw new ConcurrentModificationException();
Exception in thread "Thread-1" java.util.ConcurrentModificationException 异常原因和解决方法
标签:util 初始 ORC class 允许 one 子类 博客 遍历
原文地址:https://www.cnblogs.com/yaohuiqin/p/9355874.html