为什么我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);