Ok im trying to loop through a 2d array to copy from one to another. I can assign the integers from the first part using:
array1[i] = array2[i];
but I cannot do the same for the other part e.g:
array1[][j] = array2[][j]; //this doesn't compile
OR
array1[0]j = array2[0][j]; //creates run time error
How can I specfically copy the second part but not the first?
There is no 'first part' and 'second part' of a 2-dimensional array. There are i
rows and j
columns in an array declared x[j][i]
.
Now for the technical side:
Java does not have true 2-dimensional arrays; it has arrays of arrays, so x[rows][cols]
is an array x
of rows
arrays of cols
elements (i.e. x[rows]
is an array of arrays).
So when you performed array1[i] = array2[i]
, you were copying references to the arrays of columns in the second array.
But there is no way to do the mirror image of that -- you cannot copy references to the rows but keep the column values, because the array of rows is x
.
If you are looking for a "deep copy", you can do it manually with:
for (int row = 0; row < array1.length; row++) {
for (int col = 0; col < array1[row].length; col++) {
array2[row][col] = array1[row][col];
}
}
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