I have the following 2D Array:
int[][] matrixA = { {1, 2 ,3}, {4, 5, 6} };
And I want to create another 2D Array with the same size of matrixA
, my question is how do I do it with, the same way of an ordinary array, i.e, int[] arrayA = {10, 12, 33, 23}, int[] arrayB = new int[arrayA.length]
int[][] matrixB = new int[matrixA.length][]
Can I do it like this, only alocating one array with two positions and and leaving the rest to be filled with a for loop? Or there's a more correct and flexible way to do this?
Why not just use the ordinary multidimensional array initialization syntax?
int[][] a = {{1,2,3}, {4,5,6}};
int[][] b = new int[a.length][a[0].length];
This seems to work perfectly well. Here is a little loop that tests that all entries are indeed present, and that we don't get any AIOOBEs:
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
This, obviously assumes that you are dealing with rectangular matrices, that is, all rows must have the same dimensions. If you have some weird jagged arrays, you must use a loop to initialize each row separately.
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