Java 集合:ConcurrentModificationException
为什么我在下面的代码中得到这个Java 集合:ConcurrentModificationException,java,Java,为什么我在下面的代码中得到这个ConcurrentModificationException public static ArrayList<ArrayList<String>> buildPath(String s, String e, HashMap<String, ArrayList<String>> visited) { ArrayList<ArrayList<String>> ret = new Array
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;
}
}
}
publicstaticarraylistbuildpath(字符串s、字符串e、HashMap){
ArrayList ret=新的ArrayList();
ArrayList temp=新的ArrayList();
ArrayList tmp=新的ArrayList();
tmp.add(e);
ret.add(tmp);
布尔needStop=false;
while(true){
for(ArrayList al:ret){//并发异常
ArrayList pre_words=visted.get(al.get(al.size()-1));
for(字符串前置词:前置词){
如果(前置字比较=0){
needStop=true;
}
如果(需要停止和前置字比较)!=0){
继续;
}
ArrayList toadd=新的ArrayList(al);
添加(前置词);
温度添加(toadd);
}
}
ret=温度;
如果(需要停止){
for(阵列列表l:ret){
收藏。反面(l);
}
返回ret;
}
}
}
如果我进行以下更改,程序将正确运行:
发件人:
for(ArrayList al:ret){
致:
for(int i=0;i在使用迭代器对列表进行迭代时,您正在向列表中添加元素。这就是导致此异常的原因
非并发集合的迭代器故障很快:当它们注意到集合在迭代过程中已被修改时,会立即抛出此类异常。当您在循环过程中修改集合时,会发生ConcurrentModificationException
,这是因为不支持此行为
您的循环已结束ret
for(ArrayList<String> al : ret)
ret= temp;
然后将tmp
分配给ret
for(ArrayList<String> al : ret)
ret= temp;
下次循环(大循环而(true)
)时,修改集合
时,会得到一个ConcurrentModificationException
当你手动循环时,你没有得到它的原因
for(int i =0; i <ret.size() ; i++)
for(int i=0;i
for(int i =0; i <ret.size() ; i++)