gpt4 book ai didi

java - 为什么一个循环抛出 ConcurrentModificationException 而另一个不抛出?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:51:50 25 4
gpt4 key购买 nike

我在编写旅行商程序时遇到过这个问题。对于内部循环,我尝试了

for(Point x:ArrayList<Point>) {
// modify the iterator
}

但是当向该列表添加另一个点时导致抛出 ConcurrentModicationException

但是,当我将循环更改为

for(int x=0; x<ArrayList<Point>.size(); x++) {
// modify the array
}

循环运行良好,没有抛出异常。

都是for循环,为什么一个抛出异常,一个不抛出异常?

最佳答案

正如其他人所解释的,迭代器检测到对底层集合的修改,这是一件好事,因为它可能会导致意外行为。

想象一下这个修改集合的无迭代器代码:

for (int x = 0; list.size(); x++)
{
obj = list.get(x);
if (obj.isExpired())
{
list.remove(obj);
// Oops! list.get(x) now points to some other object so if I
// increase x again before checking that object I will have
// skipped one item in the list
}
}

关于java - 为什么一个循环抛出 ConcurrentModificationException 而另一个不抛出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2397321/

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