Syntax for creating a two-dimensional array

前端 未结 12 1198
悲&欢浪女
悲&欢浪女 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条回答
  •  情书的邮戳
    2020-11-21 18:40

    Actually Java doesn't have multi-dimensional array in mathematical sense. What Java has is just array of arrays, an array where each element is also an array. That is why the absolute requirement to initialize it is the size of the first dimension. If the rest are specified then it will create an array populated with default value.

    int[][]   ar  = new int[2][];
    int[][][] ar  = new int[2][][];
    int[][]   ar  = new int[2][2]; // 2x2 array with zeros
    

    It also gives us a quirk. The size of the sub-array cannot be changed by adding more elements, but we can do so by assigning a new array of arbitrary size.

    int[][]   ar  = new int[2][2];
    ar[1][3] = 10; // index out of bound
    ar[1]    = new int[] {1,2,3,4,5,6}; // works
    

提交回复
热议问题