为什么我在以下代码中收到此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;
}
}
}
如果我进行以下更改,程序将正确运行:
来自:
for(ArrayList<String> al : ret) {
至:
for(int i =0; i <ret.size() ; i++) {
ArrayList<String> al = ret.get(i);
最佳答案
您在使用迭代器迭代列表的同时向列表添加元素。这就是导致此异常的原因。
非并发集合的迭代器是快速失败的:一旦它们注意到集合在迭代过程中被修改,它们就会抛出这样的异常。
关于java - Collection : ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18553556/