6

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?

ramireeez
  • 152
  • 1
  • 6
  • 2
    check [this](https://stackoverflow.com/questions/12231453/syntax-for-creating-a-two-dimensional-array) out. – cosh Jan 31 '18 at 23:42

1 Answers1

7

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.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
  • Hmm i see... but what does the `[a[0].length]` in terms of coding? I'm just trying to understand it completely, and not just copy and paste it. Thanks! – ramireeez Feb 01 '18 at 00:12
  • 1
    `a` is a two-dimensional array. `a[0]` is the first "row" (if you think in row-major format). `a[0].length` is the dimension of the first row, that is, the width of the matrix. `a.length` would be the height of the matrix. `new MyType[h][w]` is the usual way to initialize two-dimensional arrays in Java. Well "usual"... Usual in those rare contexts where you initialize arrays in Java (it doesn't happen too often, because collections, and now also the stream-api, are vastly more comfortable to use). – Andrey Tyukin Feb 01 '18 at 00:16
  • Ok so if, for instance, I wanted to switch the columns for the rows of `a[]` to intialize `b[]`, it should be like this, `int[][] b = new int[a[0].length][a.length]? – ramireeez Feb 01 '18 at 00:29