我在某处读到 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
最佳答案
你误会了。
一旦你这样做了
obj1[1] = new StringBuffer("world");
您已替换了 obj1[1]
中的引用。现在这两个数组包含对不同对象的不同引用。
如果你想看到复制的是实际引用,你应该试试:
obj1[1].setLength(3);
现在 obj1[1]
和 obj2[1]
都应该包含字符串 hel
,因为你没有替换引用而是更改了内容。
关于java - System.arraycopy() 具有原始和对象引用的浅拷贝或深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43223412/