how to make copy of array instead of reference in java? [duplicate]

左心房为你撑大大i 提交于 2019-12-22 09:49:09

问题


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;

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.


回答1:


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 for loop.

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



回答2:


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.



来源:https://stackoverflow.com/questions/17534193/how-to-make-copy-of-array-instead-of-reference-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!