Skip to content
Advertisement

Java – Creating 2D Array with same size as another 2D Array

I have the following 2D Array:

JavaScript

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]

JavaScript

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?

Advertisement

Answer

Why not just use the ordinary multidimensional array initialization syntax?

JavaScript

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement