gpt4 book ai didi

java - foreach 循环中的 ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-01 07:07:05 28 4
gpt4 key购买 nike

在我的代码中:

    Collection<String> c = new ArrayList<>();
Iterator<String> it = c.iterator();
c.add("Hello");
System.out.println(it.next());

发生异常,因为我的集合在迭代器创建后发生了变化。

但是在这段代码中呢:

 ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
for (Integer integer : list) { // Exception is here
if (integer.equals(2)) {
list.remove(integer);
}
}

为什么会出现异常?

在第二个代码中,我在 for-each 循环之前对集合进行了更改。

最佳答案

在第二个循环中,原因相同 - 您要从列表中删除一个元素。

要在循环遍历列表时从列表中删除元素,可以使用标准的老式 for 循环:

for(int i=0;i<list.size();i++) {

并删除该循环内的列表项或使用ListIterator来迭代列表。

关于java - foreach 循环中的 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21612196/

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