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.
Answer
The default Object.clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable.
And when you implement Cloneable, you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.
No comments:
Post a Comment