[英]Collections: ConcurrentModificationException
Why am I getting this ConcurrentModificationException
in the following code? 为什么在以下代码中得到此ConcurrentModificationException
?
public static ArrayList<ArrayList<String>> buildPath(String s, String e, HashMap<String, ArrayList<String>> visited) {
ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> temp = new ArrayList<ArrayList<String>>();
ArrayList<String> tmp = new ArrayList<String>();
tmp.add(e);
ret.add(tmp);
boolean needStop = false;
while (true) {
for (ArrayList<String> al : ret) { //concurrent exception
ArrayList<String> pre_words = visited.get(al.get(al.size() - 1));
for (String pre_word : pre_words) {
if (pre_word.compareTo(s) == 0) {
needStop = true;
}
if (needStop && pre_word.compareTo(s) != 0) {
continue;
}
ArrayList<String> toadd = new ArrayList<String>(al);
toadd.add(pre_word);
temp.add(toadd);
}
}
ret = temp;
if (needStop) {
for (ArrayList<String> l : ret) {
Collections.reverse(l);
}
return ret;
}
}
}
If I make the following change the program runs correctly: 如果进行以下更改,程序将正确运行:
From: 从:
for(ArrayList<String> al : ret) {
to: 至:
for(int i =0; i <ret.size() ; i++) {
ArrayList<String> al = ret.get(i);
You're adding elements to a list while iterating over it using an iterator. 您要在使用迭代器对其进行迭代的同时向列表中添加元素。 This is what causes this exception. 这就是导致此异常的原因。
Iterators of non-concurrent collections are fail-fast: they throw such an exception as soon as they notice that the collection has been modified during the iteration. 非并发集合的迭代器是快速失败的:一旦发现迭代期间已经修改了集合,就会抛出异常。
A ConcurrentModificationException
occurs when you modify a Collection
while looping, this is because this behaviour is not supported. 当您在循环时修改Collection
时,会发生ConcurrentModificationException
,这是因为不支持此行为。
Your loop is over ret
你的循环结束ret
for(ArrayList<String> al : ret)
You modify tmp
您修改tmp
temp.add(toadd);
You then later assign tmp
to ret
然后,您稍后将tmp
分配给ret
ret= temp;
The next time you loop (the big loop while(true)
) you modify the Collection
you get a ConcurrentModificationException
. 下次循环时(大循环while(true)
),您修改Collection
会收到ConcurrentModificationException
。
The reason you don't get that when you loop manually 手动循环时未得到该提示的原因
for(int i =0; i <ret.size() ; i++)
Is because you are not using an Iterator
which is implicitly used in the enhanced-foreach-loop. 这是因为您没有使用在Enhanced-foreach循环中隐式使用的Iterator
。 If you do not use an Iterator
then your dodgy code cannot be checked... 如果不使用Iterator
则无法检查您的躲避代码...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.