Not able to understand array declaration int[] it2= new int[][]{{1}}[0];

arrays, java

Solution

Break the expression in parts to better understand them:

int[] first = new int[]{1}; // create a new array with one element (the element is the number one)
int[][] second = new int[][]{first}; // create an array of the arrays. The only element of the outer array is the array created in the previous step.
int[] third = second[0]; // retrieve the first (and only) element of the array of array `second`. This is the same again as `first`.

Now we will merge those expressions again. First we merge `first` and `second`:

int[][] second = new int[][]{new int[]{1}};
int[] third = second[0];

OK, no big deal. However the expression `second` can be shortend. The following is equivalent:

int[][] second = new int[][]{{1}};
int[] third = second[0];

Now we merge second and third. We can directly write:

int[] third = new int[][]{{1}}[0];

And there we are.

Problem

Please someone can help me understanding the way this array has been created. ``` int[] it2= new int[][]{{1}}[0]; ``` `it2` is one dimension array and on the right hand we have weird type of initialization. The code compiles fine, but I am able to understand how it is working.

Original source