Syntax for creating a two-dimensional array

前端 未结 12 1375
悲&欢浪女
悲&欢浪女 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:50

    Try the following:

    int[][] multi = new int[5][10];
    

    ... which is a short hand for something like this:

    int[][] multi = new int[5][];
    multi[0] = new int[10];
    multi[1] = new int[10];
    multi[2] = new int[10];
    multi[3] = new int[10];
    multi[4] = new int[10];
    

    Note that every element will be initialized to the default value for int, 0, so the above are also equivalent to:

    int[][] multi = new int[][]{
      { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
      { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
      { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
      { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
      { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
    };
    

提交回复
热议问题