增强for循环或迭代器循环特定场景下删除元素不会造成ConcurrentModificationException

先贴ArrayListL里面

private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    Itr() {}

    public boolean hasNext() {
        return cursor != size;
    }

    @SuppressWarnings("unchecked")
    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];
    }

    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();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void forEachRemaining(Consumer<? super E> consumer) {
        Objects.requireNonNull(consumer);
        final int size = ArrayList.this.size;
        int i = cursor;
        if (i >= size) {
            return;
        }
        final Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length) {
            throw new ConcurrentModificationException();
        }
        while (i != size && modCount == expectedModCount) {
            consumer.accept((E) elementData[i++]);
        }
        // update once at end of iteration to reduce heap write traffic
        cursor = i;
        lastRet = i - 1;
        checkForComodification();
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

增强for循环底层就是用的iterator的hasNext()和next()进行判断操作

hasNext方法

public boolean hasNext() { return cursor != size; }

拿cursor和list的size进行比对,如果为true,才进行next方法操作。cursor初始值是0,每进行一次正常的next操作之后,cursor+1

假设一开始list泛型是字符串里面有2个元素“a”,“b”,在增强for循环里面删除a这个元素,

for(String s:list){
    if(s.equals("a)){
        list.remove(s);
    }
}

首先第一次hasNext(),cursor=0,size=2,0!=2返回true进入next()方法,cursor=1,删除list中的"a"元素,list的size变为1

再进行第二次hasNext(),此时cursor=1,size=1,1!=1返回false,循环结束,没有抛ConcurrentModificationException异常。

 

结论:增强for循环或iterator循环时,用list去删除倒数第二个元素,都不会抛异常,但这种场景下,list中的最后一个元素不会被遍历到

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值