List<Integer>arraylist=new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4,5,6}));
for(Integer e:arraylist){
if(5==e){
System.out.println("here");
arraylist.remove(e);
}
}
System.out.println(arraylist);
List<Integer>arraylist=new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4,5,6}));
for(Integer e:arraylist){
if(4==e){
System.out.println("here");
arraylist.remove(e);
}
}
System.out.println(arraylist);
看上面的两段代码,为什么同样的形式,第一段能运行、而第二段运行不了呢。
先来解释下第二段为什么运行不了
找到反编译结果如下
List<Integer> arraylist = new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6));
Iterator var2 = arraylist.iterator();
while(var2.hasNext()) {
Integer e = (Integer)var2.next();
if (4 == e) {
System.out.println("here");
arraylist.remove(e);
}
}
System.out.println(arraylist);
可以看到,调用了ArrayList的内部类的hasNext、next方法(自行看源码,ArrayList内部有类Itr实现了Iterator接口),
源代码调用了ArrayList的remove方法、而不是Ite的remove方法,remove方法内使modCount加1,看反编译地方,当调用next方法时会核对modCount和expectedModCount是否一致,否则并分修改异常,问题出在这里。但是如果打印出来发现、remove是生效了的
那么为什么第一段代码可以正常运行呢,其实这是“凑巧了”。当remove的元素是倒数第二个时,不会发生此异常。
当删除5时,remove掉5,remove方法中size小了一个,进入下一次循环,注意,此时cursor(只在next方法中修改)在第五个位置,hasnext方法源码return cursor!=size
此时发现不满足条件,不会进入循环,自然不会调用next方法,自然没有异常。