Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 625
meteors Avatar asked Feb 17 '23 00:02

meteors


1 Answers

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);
}
like image 194
Louis Wasserman Avatar answered Feb 27 '23 09:02

Louis Wasserman