它不会抛出异常ConcurrentModificationException

Alo*_*hak 10 java iterator

我有下面的代码,我希望它抛出一个ConcurrentModificationException,但它运行成功.为什么会这样?

public void fun(){
    List <Integer>lis = new ArrayList<Integer>();
    lis.add(1);
    lis.add(2);

    for(Integer st:lis){
        lis.remove(1);
        System.out.println(lis.size());
    }
}

public static void main(String[] args) {
    test t = new test();
    t.fun();
}
Run Code Online (Sandbox Code Playgroud)

chr*_*ke- 10

该remove(int)方法List删除指定位置的元素.在开始循环之前,列表如下所示:

[1, 2]
Run Code Online (Sandbox Code Playgroud)

然后在列表上启动一个迭代器:

[1, 2]
 ^
Run Code Online (Sandbox Code Playgroud)

for然后你的循环删除位置1的元素,即数字2:

[1]
 ^
Run Code Online (Sandbox Code Playgroud)

迭代器在下一个隐含的hasNext()调用中返回false,循环终止.

ConcurrentModificationException如果您向列表中添加更多元素,您将获得一个.然后隐含next()将抛出.

作为一个注释,来自ArrayListJCF 的Javadoc :

请注意,迭代器的故障快速行为无法得到保证,因为一般来说,在存在不同步的并发修改时,不可能做出任何硬性保证.快速失败的迭代器会ConcurrentModificationException尽力而为.因此,编写依赖于此异常的程序以确保其正确性是错误的:迭代器的快速失败行为应该仅用于检测错误.

这实际上可能是Oracle ArrayList迭代器实现中的一个错误; hasNext()并没有检查修改:

public boolean hasNext() {
    return cursor != size;
}
Run Code Online (Sandbox Code Playgroud)