Java Copying Basics: Shallow, Deep, and Lazy Copy – Explained

Learn Java with an example of Shallow copy, deep copy, lazy copy.1 min


Shallow lazy and Deep copy example

In object-oriented programming, object copying is creating a copy of an existing object, the resulting object is called an object copy or simply a copy of the original object. There are several ways to copy an object, most commonly by a copy constructor or cloning.

We can define Cloning as “create a copy of object” Shallow, deep, and a lazy copy is related to the cloning process these are actually the ways for creating copy object.

Cover Image Credits: Shallow, Deep and Lazy copy — java example, Image by Author

Shallow Copy

  • clone() method of the object class supports a shallow copy of the object. If the object contains primitive as well as nonprimitive or reference type variable in shallow copy, the cloned object also refers to the same object to which the original object refers as only the object references get copied and not the referred objects themselves.
  • Whenever we use the default implementation of the clone method we get a shallow copy of the object means it creates a new instance and copies all the field of the object to that new instance and returns it as an object type, we need to explicitly cast it back to our original object. This is a shallow copy of the object.
  • That’s why the name shallow copy or shallow cloning in Java. If only primitive type fields or Immutable objects are there then there is no difference between shallow and deep copy in Java.

//code illustrating shallow copy 
public class ShallowExample { 

	private int[] data; 

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

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

The above code shows shallow copying. data simply refers to the same array as values.

Shallow Copy Example
 
This can lead to unpleasant side effects if the elements of values are changed via some other reference.

public class UsesShallowExample{ 

	public static void main(String[] args) { 
		int[] vals = {3, 7, 9}; 
		ShallowExample e = new ShallowExample(vals); 
		e.showData(); // prints out [3, 7, 9] 
		vals[0] = 13; 
		e.showData(); // prints out [13, 7, 9] 

		// Very confusing, because we didn't intentionally change anything about the object e refers to. 
	} 
} 
------------------------------------------------------------
Output 1 : [3, 7, 9]
Output 2 : [13, 7, 9]

Deep Copy

  • Whenever we need our own copy not to use default implementation we call it deep copy, whenever we need a deep copy of the object we need to implement it according to our need.
  • So for the deep copy, we need to ensure all the member classes also implement the Cloneable interface and override the clone() method of the object class.

A deep copy means actually creating a new array and copying over the values.

// Code explaining deep copy 
public class DeepCopy { 
	
	private int[] data; 

	// altered to make a deep copy of values 
	public DeepCopy(int[] values) { 
		data = new int[values.length]; 
		for (int i = 0; i < data.length; i++) { 
			data[i] = values[i]; 
		} 
	} 

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

Deep copy example 

public class UsesDeepCopy{ 

	public static void main(String[] args) { 
		int[] vals = {3, 7, 9}; 
		DeepCopy e = new DeepCopy(vals); 
		e.showData(); // prints out [3, 7, 9] 
		vals[0] = 13; 
		e.showData(); // prints out [3, 7, 9] 

	// changes in array values will not be shown in data values. 
	} 
} 

--------------------------------------------
Output 1 : [3, 7, 9]
Output 2 : [3, 7, 9]

Changes to the array values will not result in changes to the array data.

when to use what?

There is no hard and fast rule defined for selecting between shallow copy and deep copy but normally we should keep in mind that if an object has only primitive fields, then obviously we should go for shallow copy, but if the object has references to other objects, then based on the requirement, shallow copy or deep copy should be done. If the references are not updated then there is no point to initiate a deep copy.

Lazy Copy

A lazy copy can be defined as a combination of both shallow copy and deep copy. The mechanism follows a simple approach — at the initial state, a shallow copy approach is used. A counter is also used to keep track of how many objects share the data. When the program wants to modify the original object, it checks whether the object is shared or not. If the object is shared, then the deep copy mechanism is initiated.

Summary

In shallow copy, only fields of the primitive data type are copied while the object's references are not copied. Deep copy involves the copy of primitive data type as well as object references. There is no hard and fast rule as to when to do shallow copy and when to do a deep copy. Lazy copy is a combination of both of these approaches.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

adsense


Discover more from 9Mood

Subscribe to get the latest posts sent to your email.


Like it? Share with your friends!

What's Your Reaction?

Lol Lol
0
Lol
WTF WTF
0
WTF
Cute Cute
0
Cute
Love Love
0
Love
Vomit Vomit
0
Vomit
Cry Cry
0
Cry
Wow Wow
0
Wow
Fail Fail
0
Fail
Angry Angry
0
Angry
Rakshit Shah

Legend

Hey Moodies, Kem chho ? - Majama? (Yeah, You guessed Right! I am from Gujarat, India) 25, Computer Engineer, Foodie, Gamer, Coder and may be a Traveller . > If I can’t, who else will? < You can reach out me by “Rakshitshah94” on 9MOodQuoraMediumGithubInstagramsnapchattwitter, Even you can also google it to see me. I am everywhere, But I am not God. Feel free to text me.

0 Comments

Leave a Reply

Choose A Format
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Ranked List
Upvote or downvote to decide the best list item
Open List
Submit your own item and vote up for the best submission
Countdown
The Classic Internet Countdowns
Meme
Upload your own images to make custom memes
Poll
Voting to make decisions or determine opinions
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Personality quiz
Series of questions that intends to reveal something about the personality
is avocado good for breakfast? Sustainability Tips for Living Green Daily Photos Taken At Right Moment