java 如何在java中复制数组而不是引用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17534193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:14:09  来源:igfitidea点击:

how to make copy of array instead of reference in java?

javaarraysparameter-passingvariable-assignmentpass-by-reference

提问by meteors

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.

我想将给定数组的精确副本复制到某个其他数组,但是这样即使我更改了新数组中 any 的值,它也不会更改原始数组中的值。我尝试了以下代码,但在第三行之后,数组都发生了变化并获得了相同的值。

int [][]a = new int[][]{{1,2},{3,4},{5,6}};
int[][] b = a;
b[1][0] = 7;

instead of the second line I also tried

而不是第二行我也试过

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);

None of these helped. Please suggest me an appropriate method. I've tested this piece of code in eclipse scrapbook.

这些都没有帮助。请建议我一个合适的方法。我已经在 eclipse 剪贴簿中测试了这段代码。

回答by Louis Wasserman

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.

您必须复制数组的每一行;你不能复制整个数组。您可能听说过这称为深度复制。

Accept that you will need an honest-to-goodness forloop.

接受你需要一个诚实到善良的for循环。

int[][] b = new int[3][];
for (int i = 0; i < 3; i++) {
  b[i] = Arrays.copyOf(a[i], a[i].length);
}

回答by Universitas

System.arraycopy() should work for you, but it doesn't copy as a whole, it copies "from a specified position to a specified position," according to the java documentation.

System.arraycopy() 应该适合你,但它不会作为一个整体复制,它复制“从指定位置到指定位置”,根据 java 文档。