I have long being confused with whether Java's container's copy constructor is shallow copy or deep copy? Below is my understanding: ints1, ints2, ints3 are references so they lie in stack. inst1 points to some object in heap, and this object holds three anonymous references that lie in stack, and they point to Objects that have int value 0, 1, 2 seperately.
ints2 = ints1
so ints2 points to the same object as ints1. So change objects pointed by refenences in ints2 will influence those in ints2.
ints2.set(1,0+10)
will change refenence ints1.get(0)'s object.
ints3 = new ArrayList<>(ints1)
Next is my confusion.
If copy constructor is shallow copy, then although ints1 and ints3 point to different object, the two objects have same references! So any action to change objects by manipulating reference in ints1 will changes ints3, because they are pointing to the same objects.
If copy constructor is deep copy, then ints1 and ints3 will hold different references and point to different objects. Then the change in ints1 will not influence that in ints3.
According to the result, it seems that the copy constructor is deep copy, not shallow copy.
Hope someone can correct me, thanks.
import java.util.*;
public class MyClass {
public static void main(String args[]) {
List<Integer> ints1 = new ArrayList<>(Arrays.asList(0,1,2));
System.out.println(ints1);
List<Integer> ints2 = ints1;
ints2.set(0,0+10);
System.out.println(ints1);
List<Integer> ints3 = new ArrayList<>(ints1);
ints3.set(1,1+10);
System.out.println(ints1);
}
}
result
[0, 1, 2]
[10, 1, 2]
[10, 1, 2]