-1
我在編寫需要複製arraylist的代碼,但調試後發現錯誤答案我發現更改arraylist的副本正在更改原始的arraylist,但我無法找出原因ArrayList通過更改其副本更改
static void iterDeep(int level,ArrayList<ArrayList<Integer>> current){
if(current.equals(dest)){
found = 1;
printPath(current);
return;
}
if(level <= 0)
return;
for(int i=0;i<3;i++){
for(int j=0;j<2;j++){
ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(current);
if(j == 0){
for(int k=0;k<3;k++){
adj.get(k).set(i , current.get((3+k-1)%3).get(i));
// Here i am changing adj values but values in current are getting changed
}
if(!map.containsKey(adj)){
map.put(adj,current);
iterDeep(level - 1 , adj);
}
}else{
for(int k=0;k<3;k++){
adj.get(k).set(i , current.get((k+1)%3).get(i));
}
if(!map.containsKey(adj)){
map.put(adj,current);
iterDeep(level - 1 , adj);
}
}
}
}
return;
}
簡短的回答:以'新的ArrayList>(當前);''你只是創建一個新的「外部」ArrayList,內部的ArrayList仍然和以前一樣,因此包含了與'current'列表完全相同的項目。 Google深層克隆與淺層克隆。深層克隆就是你需要的。 –
Munchhausen