我在执行这段代码时得到了ConcurrentModificationException。我不明白为什么会发生这样的事情?
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);
}
}
}
}提前谢谢。
发布于 2012-11-09 19:44:40
您正在使用list引用本身删除列表中的元素,这会抛出ConcurrentModificationException。请注意,这可能有时会起作用,但并不总是如此,并且不能保证完美地工作。
此外,即使您使用Iterator来迭代列表,您仍然不应该使用list.remove,您应该只使用iterator.remove()来删除元素,否则无论您使用迭代器还是增强的for-loop,这都不会有任何区别。
因此,使用iterator.remove()删除元素。
if (index != -1) {
iterator.remove(value);
}请参阅此帖子:- java-efficient-equivalent-to-removing-while-iterating-a-collection以获取更详细的解释。
发布于 2012-11-09 19:45:33
很简单,因为您试图在迭代元素时从ArrayList中删除这些元素。要解决此问题,请使用java.util.concurrent.CopyOnWriteArrayList。希望这能有所帮助。
发布于 2012-11-09 19:45:36
发生的情况是,ArrayList迭代器并不是设计为在迭代时启用修改。
因此,为了避免来自不连贯数据的更严重的错误,它有一个修改计数,当你删除一个项目时,它会更新,当你迭代时,它会进行检查:
来自ArrayList.java:
411 public E remove(int index) {
412 rangeCheck(index);
413
414 modCount++;
415 E oldValue = elementData(index);
416
417 int numMoved = size - index - 1;
418 if (numMoved > 0)
419 System.arraycopy(elementData, index+1, elementData, index,
420 numMoved);
421 elementData[--size] = null; // Let gc do its work
422
423 return oldValue;
424 }
...
779
780 final void checkForComodification() {
781 if (modCount != expectedModCount)
782 throw new ConcurrentModificationException();
783 }在javadoc中指定:
返回的列表迭代器是快速失败的。
要避免此问题,请使用迭代器删除当前元素,而不是直接删除列表。迭代器的remove方法确保迭代器保持一致。
https://stackoverflow.com/questions/13307471
复制相似问题