Reputation: 1467
Why does this code compile?
int[] array = new int[][]{{1}}[0];
On the left side is one-dimensional array. On the right I thougth that three-dimensional, but it is not?
Upvotes: 5
Views: 184
Reputation: 234847
The right side is a one dimensional array that is the first (0th) element of the two-dimensional array
new int[][]{{1}}
To show it out more clearly lets add parenthesis
int[] array = (new int[][]{{1}}) [0];// [0] is returning first row of 2D array
// which is 1D array so it can be assigned to `array`
Upvotes: 7
Reputation: 37855
The right side expression does two things.
// instantiate new 2D array
// ┌──────┸───────┑ ┌ access zeroth element of new 2D array
// │ │ │
int[] array = new int[][]{{1}} [0];
This is basically equivalent to the following:
int[][] array2D = new int[1][1];
array2D[0][0] = 1;
int[] array = array2D[0];
Upvotes: 3
Reputation: 5249
Two dimensional array is same as one dimensional array from memory management perspective ( meaning the data is stored in a single dimension). So, first element of two dimensional array is same as the first element of one dimensional array.
Upvotes: 0