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?

1
  • 2
    check this out. Commented Jan 31, 2018 at 23:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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!
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).
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]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.