top of page
Writer's pictureSomanathan c

Shallow Vs Deep Copy

//code illustrating shallow copy


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 = {3, 7, 9};

Ex e = new Ex(vals);

e.showData(); // prints out [3, 7, 9]

vals[0] = 13;

e.showData(); // prints out [13, 7, 9]

// Very confusing, because we didn't

// intentionally change anything about

// the object e refers to.

}

}

•Whenever we use default implementation of clone method, we get shallow copy of object means it creates new instance and copies all the field of object to that new instance and returns it as object type, we need to explicitly cast it back to our original object. This is shallow copy of the object.


Output 1 : [3, 7, 9] Output 2 : [13, 7, 9]


// Code explaining deep copy

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 = {3, 7, 9};

Ex e = new Ex(vals);

e.showData(); // prints out [3, 7, 9]

vals[0] = 13;

e.showData(); // prints out [3, 7, 9]

// changes in array values will not be

// shown in data values.

}

}

Output 1 : [3, 7, 9] Output 2 : [3, 7, 9]


•Whenever we need own copy not to use default implementation we call it as deep copy, whenever we need deep copy of the object we need to implement according to our need.
































1 view0 comments

Recent Posts

See All

Useful study materials Link:

opular Python libraries Pandas and Numpy. ◾https://lnkd.in/dfrReXF7 2. Learn SQL Basics for Data Science Specialization Time to...

Microservices - Best practices

[1.] Design for failure - Microservices should be designed to tolerate failure at every level, from infrastructure to individual...

Comments


bottom of page