Jeevansai Jinne Jeevansai Jinne - 2 months ago 19
Java Question

ArrayList changes by changing its copy

I am writing a code which needs to copy an arraylist but i am getting wrong answer after debugging i found that changing a copy of arraylist is changing the original arraylist but i am not able to figure out why

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;
}

Answer

This line

ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(current);

produces a shallow copy of the list, meaning that although adding/removing elements of adj are not reflected in current, changing elements themselves have an effect on ArrayList<Integer> elements of both lists.

You need to make a method that creates a deep copy of the list, i.e. copies each individual list element into elements of adj:

static ArrayList<ArrayList<Integer>> deepCopy(ArrayList<ArrayList<Integer>> orig) {
    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
    for (ArrayList<Integer> inner : orig) {
        res.add(new ArrayList<Integer>(inner));
    }
    return res;
}