Pawel
Pawel

Reputation: 1467

One-dimensional array references to multi-dimensional array

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

Answers (3)

Ted Hopp
Ted Hopp

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

Radiodef
Radiodef

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

thestar
thestar

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

Related Questions