Advertisements
Home > ASP.NET > Deep and Shallow Copying, Difference of Shallow and Deep Copying

Deep and Shallow Copying, Difference of Shallow and Deep Copying


What is Shallow Copy?

Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

What is Deep Copy?

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

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 or pointers. A shallow copy can be made by simply copying the reference.

public class Ex{
private int[] data;

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.

Shallow

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 confusiin, 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;

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.

deep

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

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: