gpt4 book ai didi

迭代列表时的java代码优化

转载 作者:行者123 更新时间:2023-12-02 07:27:45 25 4
gpt4 key购买 nike

迭代元素列表是很常见的。检查一些条件并从列表中删除一些元素。

for (ChildClass childItem : parent.getChildList()) {
if (childItem.isRemoveCandidat()) {
parent.getChildList().remove(childItem);
}
}

但在这种情况下会抛出 java.util.ConcurrentModificationException。

在这种情况下最好的程序模式是什么?

最佳答案

使用 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]"
}

关于迭代列表时的java代码优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9530456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com