java - 它不会抛出异常 ConcurrentModificationException

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

最佳答案

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

[1, 2]

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

[1, 2]
 ^

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

[1]
 ^

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

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

请注意,来自 JCF 的 ArrayList 的 Javadoc:

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

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

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

关于java - 它不会抛出异常 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24556487/

相关文章:

java - 如何解压缩使用速记存储的图像?

java - 使用 Iterable 的类的多个迭代器

java - 如何配置eclipse支持java?

java - 始终运行相同的 Android Tab

java - 有没有其他类似的实现,比如 commons-chain?

c++ - 通过 unique_ptr vector 搜索的查找函数的返回值

c++ - 列表迭代器不可取消引用

grails - 通过迭代使每个标记

collections - 如何在迭代集合的同时修改集合?

java - 当我尝试使用 BiCionsumer 从列表中删除值时,它不起作用