Java: Declaring a multidimensional array without specifying the size of the array ( eg. new int[10][] )

和自甴很熟 提交于 2020-01-11 05:19:08

问题


I've been trying to figure out what exactly is happening here. I'm just trying to figure out what the 2 lines are doing that I've commented on below. I found this program that doesn't declare the full dimensions of the array (instead of new int[10][5]; it just decides to not declare it by saying 'new int[10][];' It's like the 2nd array length doesn't matter (changing it to 1 or 100 doesn't 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();
 }

回答1:


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

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

So, the int array in position 0 will have 1 slot for an int. The int array in position 1 will have 2 slots for an int. The overall shape will be:

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

which is hinted at with the variable name tri (it looks like a triangle)




回答2:


All new int[10][] is declaring is an array of size 10, containing null arrays.

In the for loop, the null arrays are being instantiated into ever increasing array sizes.




回答3:


It makes more 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



回答4:


It's simply declaring an array of 10 arrays. The lengths of each of those "sub" arrays can all be different.




回答5:


it's not lacking, it's basically not setting a specific amount, it isn't required because it can have many fields

and the second line

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

is setting all the fields to not null



来源:https://stackoverflow.com/questions/9896968/java-declaring-a-multidimensional-array-without-specifying-the-size-of-the-arra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!