1

I'm trying to copy a two dimensional array, then manipulate the data inside the copied version and compare it to the original one.

int[][] magicSquare2 = magicSquare;

I tried this but i realised it refers to the same object.

Vitor Hugo Schwaab
  • 1,545
  • 20
  • 31

3 Answers3

2

To create a copy of an array in Java you use System.arraycopy(). So if for exmaple you have an array (doesn't matter one or multidimentional) then,

int[] array = {4, 2, 5};
int[] copy = new int[3];

System.arraycopy(array, 0, copy, 0, 3);
Themelis
  • 4,048
  • 2
  • 21
  • 45
0

Do something like this:

int[] array = {23, 43, 55, 12};

int newLength = array.length;

int[] copiedArray = Arrays.copyOf(array, newLength);
Andres
  • 10,561
  • 4
  • 45
  • 63
0

For two dimensional arrays copy the first dimension. Then repeat the process with the elements in the first dimension. NOTE:If you don't copy the elements or clone them. They will refer to the original elements.

int[][] a2d={{0,1},{1,0}};
Int[][] copy=Arrays.copy(a2d,a2d.length);
for(int i=0;i<a2d.length;i++){
int[] e=copy[i];
//you might prefer doing null check before you proceed.
copy[i]=Arrays.copy(e,e.length);
}
D. Sikilai
  • 467
  • 1
  • 3
  • 17