Explanation of Deep and Shallow Copying

When creating copies of arrays or objects one can make a deep copy or a shallow copy. This explanation uses arrays.

Recall array variables in Java are references (some folks say pointers, but there are differences between references and points).

Object and array variables refer to the actual object or array. (In pointer terms the object and array variables store the memory address of the actual object or array. I liken this to a house on a street and the only thing in the house is a piece of paper with the address of another house on the street. To beginning programming students this seems odd, but their are valid technical reasons for this approach.)

 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) );
    }
}

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



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

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.
    }

}

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));
    }
}

The above code shows deep copying.

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

See the Wikipedia page on Deep vs. Shallow Copying. (Also includes an explanation of lazy copying.)