Java中的迭代、并发修改异常
我在 ArrayList 上使用增强的 for 循环,并希望删除一些包含特定值的元素。
当我尝试这样做时,我得到了上述异常。我环顾四周,似乎在修改集合时使用增强的 for 循环是一个坏主意。我还能怎么做呢?
感谢您的帮助。
I'm using a enhanced for loop over an ArrayList and wanted to remove some elements that contain a particular value.
When I try to do this I get the above exception. I've had a look around and it seems using a enhanced for loop while modifying the collection is a bad idea. How else would I go about this?
thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以保留要删除的项目的列表,然后在循环完成后调用removeAll。
You can keep a list of the items to be removed, then call removeAll after the loop has finished.
您应该获取集合的迭代器,遍历它并在想要删除元素时调用迭代器上的remove() 方法。请注意,并非所有迭代器实现都支持remove(),它是一个可选方法!
You should get an Iterator for the collection, walk that and call the remove() method on the iterator when you want to remove an element. Please be advised that not all Iterator implementations support remove(), it's an optional method!
您无法使用增强的 for 循环来执行此操作,因为您无权访问
迭代器
正在使用。您需要使用常规 for 循环并通过Iterator.remove()
。You cannot use the enhanced for loop to do this as you do not have access to the
Iterator
being used. You need to use a regular for loop and remove elements of theArrayList
viaIterator.remove()
.