ArrayList for循环remove元素 , 没有抛出异常

示例代码:

public class TestList {
    public static void main(String[] args) {
        List<String> a = new ArrayList<String>();
        a.add("1");
        a.add("2");
        a.add("3");
        for (String tmp : a) {
            if ("2".equals(tmp)) {
                a.remove(tmp);
            }
        }
        System.out.println(a);
    }
}

这个示例运行最后运行成功.  但是 为什么没有抛出ConcurrentModificationException异常呢?

查看代码后发现 , 问题出在这里, 

当我们遍历到 , 最后一项前一项的时候 , 这个时候size依然是3 . 而ArrayList的Iterator这里, 

public boolean hasNext() {
            return cursor != size;
        }
这里判断是否还有下一项.这里cursor是1. 很显然不等于size.

所以进入next

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];
        }
next里, cursor这时候变为2 . 
接下来我们删除这一项

public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
这里进入到fastRemove.

private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }
modCount确实是++了, 但是我们的size这时候也做了--size操作,导致size变为2.

那么下次hasNext的时候判断cursor!=size , 返回的是false. 于是其实根本没有遍历到最后一项, 从而也没有做checkForComodification的操作, 从而这里不报错.




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值