Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two dimensional array initializer followed by square brackets

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?

like image 379
user2654250 Avatar asked Dec 04 '13 14:12

user2654250


People also ask

Which is must to declare a 2D array with initializer?

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.

What is the 2nd square bracket of multi dimensional array?

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.


1 Answers

What you are doing here is:

  1. Declaring a new variable int[] it (which is a one-dimensional array)
  2. Assigning its value from the first element [0]
  3. of the two-dimensional array new int[][]
  4. which is initialized to be {{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.

like image 57
Adam Arold Avatar answered Sep 20 '22 14:09

Adam Arold