考虑:

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

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

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


当前回答

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

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

其他回答

也可以用以下方式声明它。这不是什么好设计,但很管用。

int[] twoDimIntArray[] = new int[5][10];
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};

创建5行10列的二维数组最常见的习惯用法是:

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

或者,你也可以使用下面的代码,它更类似于你所拥有的,尽管你需要显式地初始化每一行:

int[][] multD = new int[5][];
for (int i = 0; i < 5; i++) {
  multD[i] = new int[10];
}

如果你想要一些动态和灵活的东西(即你可以添加或删除列和行),你可以尝试"ArrayList of ArrayList":

public static void main(String[] args) {

    ArrayList<ArrayList<String>> arrayListOfArrayList = new ArrayList<>();

    arrayListOfArrayList.add(new ArrayList<>(List.of("First", "Second", "Third")));
    arrayListOfArrayList.add(new ArrayList<>(List.of("Fourth", "Fifth", "Sixth")));
    arrayListOfArrayList.add(new ArrayList<>(List.of("Seventh", "Eighth", "Ninth")));
    arrayListOfArrayList.add(new ArrayList<>(List.of("Tenth", "Eleventh", "Twelfth")));

    displayArrayOfArray(arrayListOfArrayList);
    addNewColumn(arrayListOfArrayList);
    displayArrayOfArray(arrayListOfArrayList);
    arrayListOfArrayList.remove(2);
    displayArrayOfArray(arrayListOfArrayList);
}

private static void displayArrayOfArray(ArrayList<ArrayList<String>> arrayListOfArrayList) {
    for (int row = 0; row < arrayListOfArrayList.size(); row++) {
        for (int col = 0; col < arrayListOfArrayList.get(row).size(); col++) {
            System.out.printf("%-10s", arrayListOfArrayList.get(row).get(col));
        }
        System.out.println("");
    }
    System.out.println("");
}

private static void addNewColumn(ArrayList<ArrayList<String>> arrayListOfArrayList) {
    for (int row = 0; row < arrayListOfArrayList.size(); row++) {
        arrayListOfArrayList.get(row).add("added" + row);
    }
}

输出:

First     Second    Third     
Fourth    Fifth     Sixth     
Seventh   Eighth    Ninth     
Tenth     Eleventh  Twelfth   

First     Second    Third     added0    
Fourth    Fifth     Sixth     added1    
Seventh   Eighth    Ninth     added2    
Tenth     Eleventh  Twelfth   added3    

First     Second    Third     added0    
Fourth    Fifth     Sixth     added1    
Tenth     Eleventh  Twelfth   added3