Deep Copy and Shallow Copy in Java



Both deep copy and shallow copy refer to creating a copy of the object given in different ways −

Shallow copy

This basically creates a new instance of the object and copies all the data from the original data set to the newly created instance. This means the newly created instance has to be specifically cast into the original object. It is also known as ‘shallow cloning’.

Example

 Live Demo

import java.util.* ;
class Demo{
   private int[] my_data;
   public Demo(int[] my_vals){
      my_data = my_vals;
   }
   public void display_data(){
      System.out.println(Arrays.toString(my_data) );
   }
}
public class Use_Demo{
   public static void main(String[] args){
      int[] my_vals = {56, 89, 91};
      Demo my_inst = new Demo(my_vals);
      my_inst.display_data();
      my_vals[0] = 65;
      my_inst.display_data();
   }
}

Output

[56, 89, 91]
[65, 89, 91]

A class named Demo contains a variable, and a constructor that copies elements of the array into a new array. Another function named ‘display_data’ displays this array of data. In the main function, an instance is created, the array is defined, and the function is called. Relevant output is displayed on the console with all the changes reflecting in it.

Deep copy

This is used when a separate copy of the data is required for different purpose or usage. All the members of the class need to implement the ‘Cloneable’ interface and override the ‘clone’ method.

Example

 Live Demo

import java.util.*;
class Demo{
   private int[] my_data;
   public Demo(int[] my_vals){
      my_data = new int[my_vals.length];
      for (int i = 0; i < my_data.length; i++){
         my_data[i] = my_vals[i];
      }
   }
   public void display_data(){
      System.out.println(Arrays.toString(my_data));
   }
}
public class Use_Demo{
   public static void main(String[] args){
      int[] my_vals = {56, 89, 91};
      Demo my_inst = new Demo(my_vals);
      my_inst.display_data();
      my_vals[0] = 65;
      my_inst.display_data();
   }
}

Output

[56, 89, 91]
[56, 89, 91]

A class named Demo contains a variable, and a constructor that iterates through the array, and copies it to another array. Another function named ‘display_data’ displays this array of data. In the main function, an instance is created, the array is defined, and the function is called. Relevant output is displayed on the console with all the changes reflecting in it.


Advertisements