考虑:
int[][] multD = new int[5][];
multD[0] = new int[10];
这就是创建5行10列的二维数组的方法吗?
我在网上看到了这段代码,但语法没有意义。
考虑:
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];
其他回答
创建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];
}
也可以用以下方式声明它。这不是什么好设计,但很管用。
int[] twoDimIntArray[] = new int[5][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
Try:
int[][] multD = new int[5][10];
注意,在代码中,只有2D数组的第一行被初始化为0。 第二行到第五行根本不存在。如果你试着打印它们,你会得到所有的null。
试试下面的方法:
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 }
};