考虑:

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

这就是创建5行10列的二维数组的方法吗?

我在网上看到了这段代码,但语法没有意义。


当前回答

试试下面的方法:

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

... 这是类似这样的东西的简称:

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];

注意,每个元素都将被初始化为int, 0的默认值,因此上述也等价于:

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 }
};

其他回答

int [][] twoDim = new int [5][5];

int a = (twoDim.length);//5
int b = (twoDim[0].length);//5

for(int i = 0; i < a; i++){ // 1 2 3 4 5
    for(int j = 0; j <b; j++) { // 1 2 3 4 5
        int x = (i+1)*(j+1);
        twoDim[i][j] = x;
        if (x<10) {
            System.out.print(" " + x + " ");
        } else {
            System.out.print(x + " ");
        }
    }//end of for J
    System.out.println();
}//end of for i

实际上,Java并没有数学意义上的多维数组。Java所拥有的只是数组的数组,每个元素也是数组的数组。这就是为什么初始化它的绝对要求是第一个维度的大小。如果指定了其余参数,则它将创建一个填充默认值的数组。

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

这也给了我们一个怪癖。子数组的大小不能通过添加更多元素来改变,但是我们可以通过分配任意大小的新数组来做到这一点。

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
int rows = 5;
int cols = 10;

int[] multD = new int[rows * cols];

for (int r = 0; r < rows; r++)
{
  for (int c = 0; c < cols; c++)
  {
     int index = r * cols + c;
     multD[index] = index * 2;
  }
}

享受吧!

试试这个方法:

int a[][] = {{1,2}, {3,4}};

int b[] = {1, 2, 3, 4};

您可以按照其他人提到的方法创建它们。还有一点需要补充:你甚至可以用每一行创建一个倾斜的二维数组,不一定有相同数量的列,就像这样:

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