top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Difference between shallow cloning and deep cloning of objects in Java?

0 votes
372 views
Difference between shallow cloning and deep cloning of objects in Java?
posted Mar 3, 2016 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

The differences are as follows:
Consider a class:

public class MyData{
  String id;
  Map myData;
}

The shallow copying of this object will be pointing to the same memory reference as the original object. So a change in myData by either original or cloned object will be reflected in other also. But in deep copying there will memory allocated and values assigned to the property will be same. Any change in object will not be reflected in other.

Shallow copying is default cloning in Java which can be achieved using Object.clone() method of Object class. For deep copying override the clone method to create new object and copy its values.

answer Mar 4, 2016 by Vishi Gulati
...