Search code examples
javalistdeep-copyshallow-copy

create a list from another list and remove elements from copied list


Suppose I have following structure and I created a list like this. If I do temp.remove(0) it won't affect on the original list but temp.get(0).vars.remove(0) will remove elements from the original list too.

I think new ArrayList(top.mids) is not doing a deep copy then how come temp.remove(0) doesn't affect on the original list?

//Top class init part and adding elements are omitted
List<Mid> temp = new ArrayList(top.mids);
temp.remove(0);
temp.get(0).bots.remove(0);


public class Top{
    List<Mid> mids = new ArrayList<Mid>();
}

public class Mid{
    List<Bot> bots = new ArrayList<Bot>();

}

public class Bot{
    int id; 
}

Solution

  • Yes your understanding is correct. List newList = new ArrayList(collection); will do a shallow copy. You can modify the newList without affecting the original collection, but they will each reference the same elements so if you modify an element in one list, the other list's element will also get the change.

    This is called a Shallow Copy. Here's a visual representation of what I've described:

    enter image description here

    The things at the bottom are the objects in your array.