我從System.arraycopy
的某處讀取了基本數據類型和對象引用的淺拷貝。帶有基元和對象引用的System.arraycopy()淺拷貝或深度拷貝
是這樣,我開始了實驗,與下面的代碼
//trying with primitive values
int a[] ={1,2,3};
int b[] = new int[a.length];
System.arraycopy(a,0,b,0,a.length);
b[0] = 9;
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
//now trying with object references
Object[] obj1 = {new Integer(3),new StringBuffer("hello")};
Object[] obj2 = new Object[obj1.length];
System.arraycopy(obj1,0,obj2,0,obj1.length);
obj1[1] = new StringBuffer("world");
System.out.println(Arrays.toString(obj1));
System.out.println(Arrays.toString(obj2));
輸出功率爲
[1, 2, 3]
[9, 2, 3]
[3, world]
[3, hello]
但我希望是
[1, 2, 3]
[9, 2, 3]
[3, world]
[3, world]
從上面的代碼,我瞭解System.arraycopy
可以爲對象引用做深層複製 如果是這樣,怎麼obj1[0] == obj2[0]
給true
「深副本元」。你怎麼能爲原語做一個深層次的拷貝呢?根據定義,它們並沒有更深層的意思。 – RealSkeptic