What is the difference between a shallow copy and a deep copy, and how do you tell which one you have been given?
A shallow copy copies the fields one level deep. A deep copy copies everything, all the way down, so that the two objects share nothing at all.
public class Main {
public static void main(String[] args) {
java.util.List<String> tags = new java.util.ArrayList<>();
tags.add("java");
Article shallow = new Article("Hello", tags);
Article deep = new Article("Hello", new java.util.ArrayList<>(tags));
shallow.tags().add("mutable");
System.out.println(shallow.tags().size()); // 2
System.out.println(deep.tags().size()); // 1
}
}
And here is the class, so you can see exactly where the sharing happens.
public class Article {
private final String title;
private final java.util.List<String> tags;
public Article(String title, java.util.List<String> tags) {
this.title = title;
this.tags = tags;
}
public java.util.List<String> tags() {
return tags;
}
}
So the shallow copy has its own reference to the list, but that reference points at the same list. So adding a tag through one of them shows up in the other. The deep copy made a new list, so the two are completely separate.
the copy the title the list
------------ ---------------- -----------------------------
shallow the same value the same list object
deep the same value a new list object
And how do you tell which one you have been given? There are three checks you can do.
The first one is to look at the code that made the copy. If it uses a copy constructor, look at whether that constructor makes a new collection or just copies the reference. If it uses the assignment, then it is a shallow copy with no doubt at all.
The second one is to change the inner object and see whether the original changes. That is the test in the code above, and it is the clearest one.
Article copy = original;
copy.tags().add("new tag");
System.out.println(original.tags().size()); // 2, they share it
The third one is to compare the inner references directly.
System.out.println(a.tags() == b.tags()); // true for a shallow copy
And the most important thing to remember is that the depth only matters when the inner object can change. A string cannot be changed, so copying a reference to a string is safe. A list can be changed, so copying a reference to a list is not safe.
So the rule to remember is this. A shallow copy shares the inner objects, and it only matters when those inner objects can change.
The last question in this topic is about implementing a deep copy safely.