Syntax for creating a two-dimensional array

前端 未结 12 1234
悲&欢浪女
悲&欢浪女 2020-11-21 18:11

Consider:

int[][] multD = new int[5][];
multD[0] = new int[10];

Is this how you create a two-dimensional array with 5 rows and 10 columns?<

12条回答
  •  猫巷女王i
    2020-11-21 18:48

    These types of arrays are known as jagged arrays in Java:

    int[][] multD = new int[3][];
    multD[0] = new int[3];
    multD[1] = new int[2];
    multD[2] = new int[5];
    

    In this scenario each row of the array holds the different number of columns. In the above example, the first row will hold three columns, the second row will hold two columns, and the third row holds five columns. You can initialize this array at compile time like below:

     int[][] multD = {{2, 4, 1}, {6, 8}, {7, 3, 6, 5, 1}};
    

    You can easily iterate all elements in your array:

    for (int i = 0; i

提交回复
热议问题