Skip to content
Advertisement

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

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?

Advertisement

Answer

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.

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