I have a problem understanding this piece of code:
int[] it = new int[][]{{1}}[0];
Why is it compileable, and how can I understand such a declaration?
Note: When you initialize a 2D array, you must always specify the first dimension(no. of rows), but providing the second dimension(no. of columns) may be omitted. In the code snippet below, we have not specified the number of columns.
The second bracket[] is known as second dimension or column of a 2D array. The first square bracket[] is used to specify the total number of arrays within a 2D array. The second square bracket[] is used to specify the total number of elements in each of these arrays.
What you are doing here is:
int[] it
(which is a one-dimensional array)[0]
new int[][]
{{1}}
So you create a two-dimensional array which you initialize to contain an array which contains 1
and at the same time you take the first element of the outer array (which is a one-dimensional array containing 1
) and assign it to your variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With