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.
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.
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);
Do something like this:
int[] array = {23, 43, 55, 12};
int newLength = array.length;
int[] copiedArray = Arrays.copyOf(array, newLength);
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);
}