Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

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.

like image 699
user1934059 Avatar asked May 18 '14 11:05

user1934059


People also ask

What does new int [] mean in Java?

new int[] means initialize an array object named arr and has a given number of elements,you can choose any number you want,but it will be of the type declared yet.

How would you declare and initialize an array of 10 ints?

To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.

Which is the proper way to declare an array?

Only square brackets([]) must be used for declaring an array.

How do you declare and initialize an array in Java?

There are several ways to declare and int array: int[] i = new int[capacity]; int[] i = new int[] {value1, value2, value3, etc}; int[] i = {value1, value2, value3, etc};


1 Answers

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.

like image 144
yankee Avatar answered Nov 15 '22 11:11

yankee