迭代元素列表很常见。检查一些条件并从列表中删除一些元素。
for (ChildClass childItem : parent.getChildList()) {
if (childItem.isRemoveCandidat()) {
parent.getChildList().remove(childItem);
}
}
但是在这种情况下抛出了java.util.ConcurrentModificationException。
在这种情况下,最好的程序模式是什么?
答案 0 :(得分:11)
使用Iterator
。如果您的列表支持Iterator.remove
,则可以使用它! 它不会抛出异常。
Iteartor<ChildClass> it = parent.getChildList().iterator();
while (it.hasNext())
if (it.next().isRemoveCandidat())
it.remove();
注意:当您“开始”迭代集合并在迭代时间内修改列表时会引发ConcurrentModificationException
(例如,在您的情况下,它没有任何与并发相关的东西。您正在使用在迭代期间List.remove
操作,在这种情况下是相同的。)。
public static void main(String[] args) {
List<Integer> list = new LinkedList<Integer>();
list.add(1);
list.add(2);
list.add(3);
for (Iterator<Integer> it = list.iterator(); it.hasNext(); )
if (it.next().equals(2))
it.remove();
System.out.println(list); // prints "[1, 3]"
}
答案 1 :(得分:1)
另一种选择是:
for(int i = parent.getChildList().length - 1; i > -1; i--) {
if(parent.getChildList().get(i).isRemoveCandidat()) {
parent.getChildList().remove(i);
}
}
答案 2 :(得分:1)
您可以使用ListItrerator
for(ListIterator it = list.listIterator(); it.hasNext();){
SomeObject obj = it.next();
if(obj.somecond()){
it.remove();
}
}
您也可以使用Iterator
。但ListItrerator
超过Iterator
的灵活性是你可以双向遍历列表。