问题描述
我正在遍历一个JRE Collection
,该集合强制执行快速失败迭代器概念,因此将抛出 ConcurrentModificationException
如果在迭代时修改了 Collection
,而不是使用 Iterator.remove()
方法。但是,如果对象满足条件,则需要删除该对象的逻辑伙伴。从而阻止伙伴也被处理。我怎样才能做到这一点?
I'm iterating over a JRE Collection
which enforces the fail-fast iterator concept, and thus will throw a ConcurrentModificationException
if the Collection
is modified while iterating, other than by using the Iterator.remove()
method . However, I need to remove an object's "logical partner" if the object meets a condition. Thus preventing the partner from also being processed. How can I do that? Perhaps by using better collection type for this purpose?
示例。
myCollection<BusinessObject>
for (BusinessObject anObject : myCollection)
{
if (someConditionIsTrue)
{
myCollection.remove(anObjectsPartner); // throws ConcurrentModificationException
}
}
谢谢。
推荐答案
您要从列表中删除一项,然后继续在同一列表中进行迭代。您可以实施两步解决方案吗?在步骤1中,将要删除的项目收集到临时集合中,在步骤2中,在识别出它们之后将其删除?
You want to remove an item from a list and continue to iterate on the same list. Can you implement a two-step solution where in step 1 you collect the items to be removed in an interim collection and in step 2 remove them after identifying them?
这篇关于如何在迭代集合时安全地从集合中删除其他元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!