考虑:
int[][] multD = new int[5][];
multD[0] = new int[10];
这就是创建5行10列的二维数组的方法吗?
我在网上看到了这段代码,但语法没有意义。
考虑:
int[][] multD = new int[5][];
multD[0] = new int[10];
这就是创建5行10列的二维数组的方法吗?
我在网上看到了这段代码,但语法没有意义。
当前回答
实际上,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 array[][] = new int[3][];
array[0] = new int[3];
array[1] = new int[2];
array[2] = new int[5];
这些类型的数组在Java中被称为锯齿数组:
int[][] multD = new int[3][];
multD[0] = new int[3];
multD[1] = new int[2];
multD[2] = new int[5];
在这个场景中,数组的每一行都包含不同数量的列。在上面的例子中,第一行包含三列,第二行包含两列,第三行包含五列。你可以在编译时初始化这个数组,如下所示:
int[][] multD = {{2, 4, 1}, {6, 8}, {7, 3, 6, 5, 1}};
你可以很容易地迭代数组中的所有元素:
for (int i = 0; i<multD.length; i++) {
for (int j = 0; j<multD[i].length; j++) {
System.out.print(multD[i][j] + "\t");
}
System.out.println();
}
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};
如果你想要一些动态和灵活的东西(即你可以添加或删除列和行),你可以尝试"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