top of page

Subscribe to Wisdom

Thanks for Subscribing!

  • Writer's picturePuru Uttam

Shallow Cloning & Deep Cloning

Cloning refers to the creation of an exact copy of an object which will be having all it's fields and content of the corresponding object.

We can achieve it in 2 ways


Shallow Cloning :

  • In it, new memory allocation never happens for the other entities, and the only reference is copied to the other entities.

  • In Shallow Cloning, a new instance is created in which all the fields of object is copied to the new instance and then this new instance is returned as object type.

  • There is a need to cast it back to our original object explicitly.

  • clone() method supports Shallow Cloning.

  • It is fast as no new memory is allocated.

  • It is less expensive.

  • That means any changes made to those objects through clone object will be reflected in original object or vice-versa. It is not fully disjoint from original object and not fully independent of original object.

//example of shallow cloning
public class Employee {

	private int[] data;

	// makes a shallow copy of values
	public Employee(int[] info) {
		data = info;
	}

	public void showData() {
		System.out.println( Arrays.toString(data) );
	}
}

In above example, data[] will share the same reference as info[]. No new memory will be allocated for it.


To understand how LinkedList works , one should know cloning and it's types.

Deep Cloning :

  • In it, new memory is allocated to the new object.

  • In Deep Cloning, a new instance is created in which all the fields of object is copied to the new instance and then this new instance is returned as object type which is having it's own reference.

  • In it, reference is not copied to the other entities.

  • We need to override clone() method to support Deep Cloning as bydefault it supports Shallow Cloning.

  • It is fast as no new memory is allocated.

  • It is highly expensive.

  • That means any changes made to those objects through clone object will not be reflected in original object or vice-versa. It is fully disjoint from original object and fully independent of original object.



//example of deep cloning
public class Employee{

	public static void main(String... args) {
		int[] values = {1, 3, 5};
		Employee e = new Employee(values);
		e.printData(); // prints out [1, 3, 5]
		values[0] = 13;
		e.printData(); // prints out [1, 3, 5]

	}
}

In above example, modification in array values will not be reflected in data values.



The objects which implement Cloneable interface are only eligible for cloning process. Cloneable interface is a marker interface which is used to provide the marker to cloning process.



9 views0 comments

Recent Posts

See All

Comments


Modern Digital Watch
bottom of page