java ArrayList.remove 和 Iterator.remove 区别

foreach 遍历 ArrayList 的时候  用ArrayList.remove 做删除操作会异常的

直接用 Iterator 遍历  Iterator.remove  是不会异常的

众所周知,foreach 本质上就是 Iterator 的语法糖    那么为什么会出现这种情况呢?

 ArrayList 的  Iterator 返回的是 Itr 类的实例

public Iterator<E> iterator() {
return new Itr();
}


实例化Itr的时候 记录了一个变量
int expectedModCount =modCount;

其中 modCount 是ArrayList的属性 expectedModCount 是Itr的属性
ArrayList.add   ArrayList.remove 等操作  都执行了 modCount++; 操作
就是说
expectedModCount 记录的是 new Itr 之前的ArrayList修改操作次数
至于之后做的 modCount++; 则不知道
然鹅,每次Itr.next() 操作中  都判断了 
if (modCount != expectedModCount)
throw new ConcurrentModificationException();

哈哈 找到foreach报错原因了吧


那么 为什么 Iterator.remove 不报错呢? 实际上
Iterator.remove内部也调用了ArrayList.remove 只不过后面又执行了 expectedModCount=modCount 









posted @ 2020-11-01 13:11  dint  阅读(642)  评论(0编辑  收藏  举报