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?
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`
int[][]{{1}} - I see two square brackets, so I suppose two-dimensional array. Why it is so? Could you explain more?int array = new int[]{1, 2, 4} [0];. First the array is created with three elements and I choose first element from this. It is only int.new int[][]{{1}} (with or without parentheses around it) is an array creation expression and the trailing [0] is simply selecting the element at index 0 of the just-created array.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];
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.
int[][] array = new int[5][10] will pass, int[] = new int[3][2] will not. The sizes has to match, but in my example, in my opinion it does not.int[] arrayX = new int[3][2]; will not compile because you are trying to pass two dimensional array of integers to one dimensional one.