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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With