Java中的并发修改异常
发布时间:2020-12-15 04:59:11 所属栏目:Java 来源:网络整理
导读:参见英文答案 Iterating through a Collection,avoiding ConcurrentModificationException when removing objects in a loop????????????????????????????????????23个 我在执行此代码时收到ConcurrentModificationException.我无法弄清楚它为什么会发生? p
参见英文答案 >
Iterating through a Collection,avoiding ConcurrentModificationException when removing objects in a loop????????????????????????????????????23个
我在执行此代码时收到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); } } } } 提前致谢. 解决方法
您正在使用列表引用本身删除列表中的元素,这可能会抛出ConcurrentModificationException.请注意,这可能有时会起作用,但并非总是如此,并且无法保证完美运行.
此外,即使您使用Iterator迭代列表,您仍然不应该使用list.remove,您应该只使用iterator.remove()来删除元素,否则它将没有任何区别,无论您使用迭代器还是增强的for循环. 因此,使用iterator.remove()删除元素. if (index != -1) { iterator.remove(value); } 有关详细说明,请参阅此帖子: – java-efficient-equivalent-to-removing-while-iterating-a-collection. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |