4

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.

meteors
  • 1,747
  • 3
  • 20
  • 40

2 Answers2

11

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);
}
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • 1
    Thank you @Louis I found out that Arrays.copy and system.arraycopy work only for 1d array as 2d array is just a 1d array of arrays. – meteors Jul 08 '13 at 19:26
-1

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.

Universitas
  • 493
  • 2
  • 5
  • 21
  • 2
    It does not do a deep copy – Andreas Fester Jul 08 '13 at 19:19
  • @Universitas I tried that but it didn't help. – meteors Jul 08 '13 at 19:23
  • @meteors The problem is not the "position" parameters of `System.arraycopy()`, but the fact that it does a shallow copy only, copying only the first level of an n-dimensional array with n > 1. Check out the "duplicate link" from the comments above and the answer from @Louis – Andreas Fester Jul 08 '13 at 19:25