集合迭代器删除集合元素出现异常

问题:

  1. 使用集合的remove删除元素:出现ConcurrentModificationException异常
    代码如下:
public class Test {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        for(int i=0;i<5;i++){
            arrayList.add(i);
        }
        Iterator iterator = arrayList.iterator();
        while (iterator.hasNext()) {
            Object next =  iterator.next();
            int num=(int)next;
            if(num==4){
                arrayList.remove(4);
            }
        }
    }
}

分析:

  1. 在创建迭代器时会执行int expectedModCount = modCount;
  2. 当cursor不等于size时,即有下一个元素时,hasNext() 返回true
  3. 然后执行next(),在next()方法中会先执行checkForComodification(),而在这个方法中会判断modCount != expectedModCount
  4. 当我们执行arrayList.remove(4);语句,会执行 modCount++;
  5. 最终导致modCount != expectedModCount为true,抛出ConcurrentModificationException异常

hasNext()、next()、checkForComodification(),ArrayList的remove()源码:

        public boolean hasNext() {
           //size是指集合的元素个数
           //cursor是指集合下一个元素的索引
            return cursor != size;
        }
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
        final void checkForComodification() {
            //
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
 public E remove(int index) {
        ...
        modCount++;
        ...
    }

解决方法:

使用迭代器的remove,例如 iterator.remove(4)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值