AlexWei
AlexWei

Reputation: 1103

Creating Two-Dimensional Array in java & index pos

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 .

Upvotes: 1

Views: 164

Answers (1)

Óscar López
Óscar López

Reputation: 236114

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.

Upvotes: 1

Related Questions