Is clone()
in java a shallow copy?
Eventually this gets to the clone() method of Object (the uppermost class), which creates a new instance of the same class as the object and copies all the fields to the new instance (a "shallow copy").
I read this from wikipedia.
I don't understand why it is a shallow copy. clone()
will create a new instance with all fields. Is this just a deep copy? confused. Need some explanation for me.
What
clone
does is defined for each object that chooses to support clone. Object.clone is protected, so no object allows clone unless someone has specifically defined it.Some objects do not provide a deep copy. For example, an ArrayList will clone the list, but not the elements in the list. The following is from the JavaDoc for ArrayList:
As an aside, I'm surprised nobody has mentioned Joshua Bloch's views on Cloneable
It is a shallow copy because it only copies reference to other objects. Say we have these classes :
And now we make a clone of an instance of A :
The B instance in firstA and secondA will be the same. You won't have a copy of the B instance. This is why clone() is said to do shallow copy.
The diagrams on the page you linked should help you understand all that.
The default implementation of Object.clone() is a shallow copy. This behavior is still useful for types that have a large number of primitive fields or Immutable fields. You can look at How to properly override clone method? for how to properly override it. After calling super.clone(), then casting the resulting object, you can then clone deeper as needed.
Implicitly, the value of clone diminishes as the number of complex, mutable fields on your type increases.
clone() creates copy of all fields. Java have primitive types and refences - when you clone your object you get a new object with copies of all primitive field (it is like deep copy) but also you have copy of all refernce fields. So in result you get two objects with they own copies of primitives and copies of references to the same objects - both original and copied object will use the same objects.