如何制作数组的副本而不是在Java中引用?
我想将给定数组精确复制到其他数组,但是即使我更改了新数组中任何值,也不会更改原始数组中的值。
我尝试了以下代码,但在第三行之后,数组都发生了更改,并获得了相同的值。
I want to make an exact copy of given array to some other array but such that even though I change the value of any in the new array it does not change the value in the original array. I tried the following code but after the third line both the array changes and attains the same value.
int [][]a = new int[][]{{1,2},{3,4},{5,6}};
int[][] b = a;
b[1][0] = 7;
我也尝试过第二行
int[][] b = (int[][])a.clone();
int [][] b = new int [3][2];
System.arraycopy(a,0,b,0,a.length);
int [][] b = Arrays.copyOf(a,a.length);
这些都没有帮助。请给我建议一个合适的方法。我已经在Eclipse剪贴簿中测试过这段代码。
None of these helped. Please suggest me an appropriate method. I've tested this piece of code in eclipse scrapbook.
您必须复制数组的每一行;您无法复制整个阵列。您可能已经听说过这种称为深度复制的方法。
You have to copy each row of the array; you can't copy the array as a whole. You may have heard this called deep copying.
接受 $ $ c>循环需要诚实至善的经历
Accept that you will need an honest-to-goodness for
loop.
int[][] b = new int[3][];
for (int i = 0; i < 3; i++) {
b[i] = Arrays.copyOf(a[i], a[i].length);
}