Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

In shallow Copy, variables Original object (A) and Cloned object (B) refer to different areas of memory, when B is assigned to A the two variables refer to the same area of memory. Later modifications to the contents of either are instantly reflected in the contents of other, as they share contents. In Deep copy, when B is assigned to A the values in the memory area which A points to are copied into the memory area to which B points. Later modifications to the contents of either remain unique to A or B; the contents are not shared.

 

Examples

// Shallow copy example 
// A shallow copy can be made by simply copying the reference. 
// data simply refers to the same array as values. 
public class Ex { 
  private int[] data; 
  
  // Makes a shallow copy of values 
  public Ex(int[] values) { 
    data = values; 
  } 
  
  public void showData() { 
    System.out.println( Arrays.toString(data) ); 
  }
}

public class UsesEx{

  public static void main(String[] args) {

    int[] vals = {-5, 12, 0};
    Ex e = new Ex(vals);
    
    e.showData(); // prints out [-5, 12, 0]
    vals[0] = 13;
    
    e.showData(); // prints out [13, 12, 0]
  }
}

 

Shallow copy can lead to unpleasant side effects as shown in the above example if the elements of values are changed via some other reference.

A deep copy means actually creating a new array and copying over the values. Changes to the array values refers to will not result in changes to the array data refers to.

// Deep copy example 
public class Ex { 
  private int[] data; 
  
  // Deep copy of values
  public Ex(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) ); 
  }
}

public class UsesEx{

  public static void main(String[] args) {

    int[] vals = {-5, 12, 0};
    Ex e = new Ex(vals);
    
    e.showData(); // prints out [-5, 12, 0]
    vals[0] = 13;
    
    e.showData(); // prints out [-5, 12, 0]
  }
}