在Java中并发修改异常 [英] Concurrent Modification Exception in Java

查看:193
本文介绍了在Java中并发修改异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到ConcurrentModificationException的同时执行此code。我无法弄清楚它为什么发生?

I am getting the ConcurrentModificationException while executing this code. I am unable to figure out why it is happening?

private void verifyBookingIfAvailable(ArrayList<Integer> list, int id) {

        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
                int value = iterator.next();
                if (value == id) {
                    int index = list.indexOf(id);

                    if (index != -1) {
                        list.remove(index);
                    }
                }
        }
    }

先谢谢了。

推荐答案

您正在使用的列表引用本身,它可以扔在列表中删除元素 ConcurrentModificationException的。需要注意的是,这有时可能会工作,但不总是,并且不能保证正常工作。

You are removing the element in the list using the list reference itself, which can throw ConcurrentModificationException. Note that, this might work sometimes, but not always, and is not guaranteed to work perfectly.

此外,即使您使用的Iterator 来迭代列表,你还是不应该使用 list.remove ,你应该只使用 iterator.remove()删除元素,否则将没有任何区别,无论你使用迭代或增强的for循环。

Also, even though you use Iterator to iterate your list, you still shouldn't use list.remove, you should only use iterator.remove() to remove the elements, else it won't make any difference, whether you use iterators or enhanced for-loop.

所以,使用 iterator.remove()删除元素。

if (index != -1) {
    iterator.remove(value);
}

请参阅这篇文章: - <一个href=\"http://stackoverflow.com/questions/223918/efficient-equivalent-for-removing-elements-while-iterating-the-collection\">java-efficient-equivalent-to-removing-while-iterating-a-collection对于更详细的解释。

See this post: - java-efficient-equivalent-to-removing-while-iterating-a-collection for more detailed explanation.

这篇关于在Java中并发修改异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆