سؤال

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; 
}
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

The statement

new ArrayList(top.mids) is not doing a deep copy

refers to the fact that while you indeed have a new list containing all the items of the old list, the items in the new list refer to the same instances in memory as the old list did.

This means that while you can modify the new list's contents (i.e. references to objects) without any effect on the old list, modifying the objects inside that list will be visible as well when accessing them via the old list.

To make this clear I'd like to go with an example:

List<X> oldList = Arrays.asList(new X("1"), new X("2"));
List<X> newList = new ArrayList<X>(oldList);

newList.remove(0);
System.out.println(newList.size()); // Prints 1
System.out.println(oldList.size()); // Prints 2

System.out.println(oldList.get(1).getValue()); // Prints 2
newList.get(0).setValue("3");
System.out.println(oldList.get(1).getValue()); // Prints 3
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top