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.
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.
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.
Only square brackets([]) must be used for declaring an array.
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};
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.
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