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.
The default implementation of Java Object clone() method is using shallow copy. It's using reflection API to create the copy of the instance.
Shallow Copy/ Cloning It means it creates a new instance and copies all the fields of the object to that new instance where both are referencing to the same memory in heap memory. clone() method of the object class supports the shallow copy of the object.
In shallow copy, only fields of primitive data type are copied while the objects references are not copied. Deep copy involves the copy of primitive data type as well as object references.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With