Java: declaring a multidimensional array without specifying the size of the array (for example, new int [10] [])

I tried to find out what exactly is happening here. I'm just trying to figure out what 2 lines are doing, which I commented below. I found this program that does not declare the full size of the array (instead of the new int [10] [5]; it simply decides not to declare it by saying "new int [10] [];" This is like the second length of the array does not matter (change its 1 or 100 does not affect the output).

int[][] tri = new int[10][]; //this lack of giving the size of the 2nd array is strange for (int r=0; r<tri.length; r++) { tri[r] = new int[r+1]; //I'm not sure what this line is doing really } for (int r=0; r<tri.length; r++) { for (int a=0; a<tri[r].length; a++) { System.out.print(tri[r][a]); } System.out.println(); } 
+4
source share
5 answers

The first line creates an array of int arrays. There are 10 slots for the created arrays.

The third line creates a new int array and puts it in one of the slots that you made at the beginning. The new int array has r + 1 spaces for ints in it.

So, the int array at position 0 will have 1 slot for int. The int array at position 1 will have 2 slots for int. The general form will be:

 [ [0], [0,0], [0,0,0], ..., [0,0,0,0,0,0,0,0,0,0] ] 

which alludes to the name of the tri variable (it looks like a triangle)

+8
source

Everything new int[10][] declares an array of size 10 containing null arrays.

In a for loop, null arrays are created into ever-increasing array sizes.

+2
source

This makes sense if you think of a multidimensional array as an array of arrays:

 int [][] tri = new int[10][]; // This is an array of 10 arrays tri[r] = new int[r+1]; // This is setting the r'th array to // a new array of r+1 ints 
+2
source

It just declares an array of 10 arrays. The lengths of each of these "under" arrays can be different.

+1
source

it is not enough, it basically does not set a certain amount, it is not required because it can have many fields

and the second line

 tri[r] = new int[r+1]; 

sets all fields not null

0
source

Source: https://habr.com/ru/post/1403741/


All Articles