28 Aug 2017

Difference between Shallow copy and Deep copy

An object copy is a process where a data object has its attributes copied to another object of the same data type.
Shallow Copy :
  1. Shallow copying is creating a new object and then copying the non static fields of the current object to the new object. If the field is a value type, a bit by bit copy of the field is performed. If the field is a reference type, the reference is copied but the referred object is not, therefore the original object and its clone refer to the same object. A shallow copy of an object is a new object whose instance variables are identical to the old object.
  2. The situations like , if you have an object with values and you want to create a copy of that object in another variable from same type, then you can use shallow copy, all property values which are of value types will be copied, but if you have a property which is of reference type then this instance will not be copied, instead you will have a reference to that instance only.
  3.  A shallow copy can be made by simply copying the reference.
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]
        // Very confusing, because I didn't intentionally change anything about the 
        // object e refers to.
    }

}

Deep Copy : 
  1. Deep copy is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type, a bit by bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed. A deep copy of an object is a new object with entirely new instance variables, it does not share objects with the old.
  2. A deep copy means actually creating a new array and copying over the values.

public class Ex{
    
    private int[] data;

    // altered to make a 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 [13, 12, 0]
        // Very confusing, because I didn't intentionally change anything about the 
        // object e refers to.
    }

}

No comments:

Post a Comment

commnet here