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

来源:互联网 发布:百度地图数据采集器 编辑:程序博客网 时间:2024/04/29 09:13

示例代码:

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