我正在学习深复制和浅复制。
如果我们有两个数组:
int[]arr1={1,2,3,4,5};
int[]arr2={1,2,3,4,5};
问题:两个数组都指向相同的引用[1][2][3][4][5]
。
如果我更改 arr1[2]
会发生什么?它会更改 arr2[2]
吗?
当我们将一个数组(随机数组,不一定是 arr1
或 arr2
)从 main 传递到方法时,编译器会进行浅复制数组到方法,对吗?
如果 Java 编译器被重写以生成数组数据的深层副本并将其发送到该方法。 main 中的原始数组会发生什么情况?我认为原始数组可能会根据方法发生变化并传回main。我不确定。
最佳答案
Question: Both arrays point to the same references [1][2][3][4][5].
不完全是。您的数组具有相同的内容。话虽这么说,根据您的初始化,他们使用的数据不是共享的。然而,像这样初始化它会:
int[]arr1={1,2,3,4,5};
int[] arr2 = arr1
What will happen if I change arr1[2]?Does it changes arr2[2]?
根据上述问题的答案,不会。但是,如果您要按照我指出的那样更改初始化机制,那就会的。
When we pass an array (random array, not necessarily arr1 or arr2) from main into a method the compiler makes a shallow copy of the array to the method, right?
您的方法将收到一个可以查找数组的位置,不会进行任何复制。
If the Java compiler was re-written to make and send a deep copy of the array data to the method. What happens to the original array in the main? I think the original array may change according to the method and pass back into the main. I am not sure.
如果您要创建数组的深拷贝并将其发送到您的方法,并且您的方法将在该副本上运行,那么原始数组应该保持不变。
关于java - 数组深拷贝和浅拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22217432/