迭代元素列表是很常见的。检查一些条件,并从列表中删除一些元素。
for (ChildClass childItem : parent.getChildList()) {
if (childItem.isRemoveCandidat()) {
parent.getChildList().remove(childItem);
}
}但在本例中抛出了java.util.ConcurrentModificationException。
在这种情况下,最好的编程模式是什么?
发布于 2012-03-02 16:59:30
使用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]"
}发布于 2012-03-02 17:03:37
另一种选择是:
for(int i = parent.getChildList().length - 1; i > -1; i--) {
if(parent.getChildList().get(i).isRemoveCandidat()) {
parent.getChildList().remove(i);
}
}发布于 2012-03-02 17:10:20
您可以使用ListItrerator
for(ListIterator it = list.listIterator(); it.hasNext();){
SomeObject obj = it.next();
if(obj.somecond()){
it.remove();
}
}您也可以使用Iterator。但是,与Iterator相比,ListItrerator的灵活性在于您可以通过两种方式遍历列表。
https://stackoverflow.com/questions/9530456
复制相似问题