加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 它不会抛出异常ConcurrentModificationException

发布时间:2020-12-14 16:28:57 所属栏目:Java 来源:网络整理
导读:我有下面的代码,我会期望它抛出一个ConcurrentModificationException,但它运行成功.为什么会发生这种情况? public void fun(){ List Integerlis = new ArrayListInteger(); lis.add(1); lis.add(2); for(Integer st:lis){ lis.remove(1); System.out.printl
我有下面的代码,我会期望它抛出一个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()将会抛出.

作为一个注释,从Javadoc的ArrayList从JCF:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读