考虑:
int[][] multD = new int[5][];
multD[0] = new int[10];
这就是创建5行10列的二维数组的方法吗?
我在网上看到了这段代码,但语法没有意义。
考虑:
int[][] multD = new int[5][];
multD[0] = new int[10];
这就是创建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
其他回答
在Java中,二维数组可以声明为与一维数组相同。在一维数组中,你可以这样写
int array[] = new int[5];
其中int是一个数据类型,array[]是一个数组声明,new array是一个数组,它的对象有五个索引。
这样,就可以像下面这样编写一个二维数组。
int array[][];
array = new int[3][4];
这里数组是int数据类型。我首先声明了该类型的一维数组,然后创建了一个3行4列的数组。
在代码中
int[][] multD = new int[5][];
multD[0] = new int[10];
意味着您已经创建了一个二维数组,有5行。在 第一行有10列。在Java中,您可以根据需要为每一行选择列大小。
您可以按照其他人提到的方法创建它们。还有一点需要补充:你甚至可以用每一行创建一个倾斜的二维数组,不一定有相同数量的列,就像这样:
int array[][] = new int[3][];
array[0] = new int[3];
array[1] = new int[2];
array[2] = new int[5];
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
试试这个方法:
int a[][] = {{1,2}, {3,4}};
int b[] = {1, 2, 3, 4};
也可以用以下方式声明它。这不是什么好设计,但很管用。
int[] twoDimIntArray[] = new int[5][10];