1

I already know that how to initialize two dimensional array. But I don't figure out it why.For ex:

I think the initialization should be :

int [][]b=new int[][5];

instead of

int [][]b=new int[5][];

based on following reasons:

assume int[] ==Class A

  A b[]=new A[5];

when I replace A with int [],the outcome is

 (int[])b=new (int[])[5];

So where I miss the point? Thanks a lot .

1
  • You missed the fact that new int[M][N] means "a length-M array of length-N arrays", not vice versa. Commented Sep 14, 2014 at 12:53

1 Answer 1

1

A two-dimensional array in Java is just an array of arrays. It's easier to understand if we visualise the first-level array as holding the rows of a matrix, and the second-level array as holding the columns in each row - this makes sense, because when we access an element in position m[i][j] we're referring to the row i and the column j. When we write this:

int[][] b = new int[5][];

… We're stating that the array will have 5 rows, but we don't know in advance how many columns will have each row (this number can be variable!). On the other hand, when we say this:

int[][] b = new int[5][5];

… We're stating from the beginning that there will be 5 rows, each one with 5 columns. Now you can see why this doesn't make sense:

int[][] b = new int[][5];

… It'd be like saying: we want to have 5 columns, but we don't know how many rows there will be - and remember, a two-dimensional array is an array of rows, where each row contains another array representing the columns in that row.

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

5 Comments

Suggest finding a better term than "rows" - that implies a direction (i.e. rows vs. columns), which is not the case.
@OliverCharlesworth I'm appealing to an intuitive notion for the explanation, I can't think of another word without resorting to a direction
How about "outer" and "inner"?
@OliverCharlesworth it's less clear IMHO. I'm sticking with "rows" and "columns", but adding a clarification at the beginning that this is just a way to visualise what's happening.
@ÓscarLópez thanks for making the idea clear for me.

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.