Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is clone() in java shallow copy?

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.

like image 851
Josh Morrison Avatar asked Mar 11 '11 22:03

Josh Morrison


People also ask

Is clone Java deep copy or shallow copy?

The default implementation of Java Object clone() method is using shallow copy. It's using reflection API to create the copy of the instance.

What is shallow clone in Java?

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.

What is shallow clone and deep clone in Java?

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.


1 Answers

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.

like image 153
Chris Jester-Young Avatar answered Oct 02 '22 18:10

Chris Jester-Young