问题描述
我在执行此代码时收到 ConcurrentModificationException.我无法弄清楚为什么会这样?
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);
}
}
}
}
提前致谢.
推荐答案
您正在使用 list
引用本身删除列表中的元素,这会抛出 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()
删除元素.
So, use iterator.remove()
to remove elements.
if (index != -1) {
iterator.remove(value);
}
见这篇文章:- java-efficient-equivalent-to-removing-while-itering-a-collection 以获得更详细的解释.
See this post: - java-efficient-equivalent-to-removing-while-iterating-a-collection for more detailed explanation.
这篇关于Java中的并发修改异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!