我从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