JAVA中的拷貝分為淺拷貝和深拷貝兩種,從名字上已經可以看出它們的區別:淺拷貝僅僅拷貝對象的引用,而不是對象本身,而深拷貝則是在內存中重新建立一個對象副本,與原對象無關。接下來我們分別看一下如何實現淺拷貝和深拷貝。
1. 實現淺拷貝
public class ShallowCopy implements Cloneable { private int[] data; public ShallowCopy(int[] data) { this.data = data; } public int[] getData() { return data; } public Object clone() throws CloneNotSupportedException { return super.clone(); } } public class Main { public static void main(String[] args) throws CloneNotSupportedException { int[] orig = {1, 2, 3, 4, 5}; ShallowCopy sc = new ShallowCopy(orig); ShallowCopy sc1 = (ShallowCopy) sc.clone(); System.out.println(Arrays.toString(sc.getData())); System.out.println(Arrays.toString(sc1.getData())); orig[0] = 100; System.out.println(Arrays.toString(sc.getData())); System.out.println(Arrays.toString(sc1.getData())); } }
2. 實現深拷貝
public class DeepCopy implements Cloneable { private int[] data; public DeepCopy(int[] data) { this.data = new int[data.length]; System.arraycopy(data, 0, this.data, 0, data.length); } public int[] getData() { return data; } public Object clone() throws CloneNotSupportedException { DeepCopy copy = (DeepCopy) super.clone(); copy.data = new int[this.data.length]; System.arraycopy(this.data, 0, copy.data, 0, this.data.length); return copy; } } public class Main { public static void main(String[] args) throws CloneNotSupportedException { int[] orig = {1, 2, 3, 4, 5}; DeepCopy dc = new DeepCopy(orig); DeepCopy dc1 = (DeepCopy) dc.clone(); System.out.println(Arrays.toString(dc.getData())); System.out.println(Arrays.toString(dc1.getData())); orig[0] = 100; System.out.println(Arrays.toString(dc.getData())); System.out.println(Arrays.toString(dc1.getData())); } }
通過上面的代碼我們可以看出,淺拷貝只是賦予對象一個新的引用地址,也就是說一個對象的改變會影響到另一個對象的值,而深拷貝則是在內存中新開辟一塊區域,重新為對象分配空間,兩者的區別在于深拷貝重新分配的空間與原對象無關,對原對象的改變不會影響到深拷貝對象的值。