//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.
Comments