简体   繁体   English

Java中创建二维数组的语法

[英]Syntax for creating a two-dimensional array in Java

Consider:考虑:

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

Is this how you create a two-dimensional array with 5 rows and 10 columns?这就是创建 5 行 10 列的二维数组的方式吗?

I saw this code online, but the syntax didn't make sense.我在网上看到这段代码,但是语法没有意义。

Try the following:请尝试以下操作:

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

... which is a short hand for something like this: ...这是这样的事情的简写:

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

Note that every element will be initialized to the default value for int , 0 , so the above are also equivalent to:请注意,每个元素都将初始化为int0的默认值,因此上述内容也等效于:

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

We can declare a two dimensional array and directly store elements at the time of its declaration as:我们可以声明一个二维数组,并在声明时直接存储元素为:

int marks[][]={{50,60,55,67,70},{62,65,70,70,81},{72,66,77,80,69}};

Here int represents integer type elements stored into the array and the array name is 'marks'.这里int表示存储在数组中的整数类型元素,数组名称为 'marks'。 int is the datatype for all the elements represented inside the "{" and "}" braces because an array is a collection of elements having the same data type. int是“{”和“}”大括号内表示的所有元素的数据类型,因为数组是具有相同数据类型的元素的集合。

Coming back to our statement written above: each row of elements should be written inside the curly braces.回到我们上面写的语句:每一行元素都应该写在花括号内。 The rows and the elements in each row should be separated by a commas.行和每行中的元素应该用逗号分隔。

Now observe the statement: you can get there are 3 rows and 5 columns, so the JVM creates 3 * 5 = 15 blocks of memory.现在观察语句:您可以得到 3 行 5 列,因此 JVM 创建 3 * 5 = 15 个内存块。 These blocks can be individually referred ta as:这些块可以单独称为:

marks[0][0]  marks[0][1]  marks[0][2]  marks[0][3]  marks[0][4]
marks[1][0]  marks[1][1]  marks[1][2]  marks[1][3]  marks[1][4]
marks[2][0]  marks[2][1]  marks[2][2]  marks[2][3]  marks[2][4]


NOTE:笔记:
If you want to store n elements then the array index starts from zero and ends at n-1 .如果要存储n 个元素,则数组索引从零开始并以n-1结束。 Another way of creating a two dimensional array is by declaring the array first and then allotting memory for it by using new operator.创建二维数组的另一种方法是先声明数组,然后使用 new 运算符为其分配内存。

int marks[][];           // declare marks array
marks = new int[3][5];   // allocate memory for storing 15 elements

By combining the above two we can write:结合以上两者,我们可以写出:

int marks[][] = new int[3][5];

You can create them just the way others have mentioned.您可以按照其他人提到的方式创建它们。 One more point to add: You can even create a skewed two-dimensional array with each row, not necessarily having the same number of collumns, like this:还要补充一点:您甚至可以为每一行创建一个倾斜的二维数组,不一定具有相同数量的列,如下所示:

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

The most common idiom to create a two-dimensional array with 5 rows and 10 columns is:创建具有510列的二维数组的最常见习惯用法是:

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

Alternatively, you could use the following, which is more similar to what you have, though you need to explicitly initialize each row:或者,您可以使用以下内容,这与您拥有的内容更相似,但您需要显式初始化每一行:

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

It is also possible to declare it the following way.也可以通过以下方式声明它。 It's not good design, but it works.这不是好的设计,但它有效。

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

Try:尝试:

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

Note that in your code only the first line of the 2D array is initialized to 0. Line 2 to 5 don't even exist.请注意,在您的代码中,只有二维数组的第一行被初始化为 0。第 2 行到第 5 行甚至不存在。 If you try to print them you'll get null for everyone of them.如果您尝试打印它们,那么每个人都会得到null

In Java, a two-dimensional array can be declared as the same as a one-dimensional array.在 Java 中,可以将二维数组声明为与一维数组相同的声明。 In a one-dimensional array you can write like在一个一维数组中,你可以这样写

  int array[] = new int[5];

where int is a data type, array[] is an array declaration, and new array is an array with its objects with five indexes.其中 int 是一种数据类型,array[] 是一个数组声明,而new array是一个数组,其对象具有五个索引。

Like that, you can write a two-dimensional array as the following.像这样,您可以编写一个二维数组,如下所示。

  int array[][];
  array = new int[3][4];

Here array is an int data type.这里的array是一个 int 数据类型。 I have firstly declared on a one-dimensional array of that types, then a 3 row and 4 column array is created.我首先声明了该类型的一维数组,然后创建了一个 3 行 4 列数组。

In your code在你的代码中

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

means that you have created a two-dimensional array, with five rows.意味着您已经创建了一个二维数组,有五行。 In the first row there are 10 columns.第一行有 10 列。 In Java you can select the column size for every row as you desire.在 Java 中,您可以根据需要选择每一行的列大小。

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

Enjoy!享受!

Try this way:试试这个方法:

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

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

These types of arrays are known as jagged arrays in Java:这些类型的数组在 Java 中称为锯齿数组:

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

In this scenario each row of the array holds the different number of columns.在这种情况下,数组的每一行都包含不同数量的列。 In the above example, the first row will hold three columns, the second row will hold two columns, and the third row holds five columns.在上面的例子中,第一行将包含三列,第二行将包含两列,第三行将包含五列。 You can initialize this array at compile time like below:您可以在编译时初始化此数组,如下所示:

 int[][] multD = {{2, 4, 1}, {6, 8}, {7, 3, 6, 5, 1}};

You can easily iterate all elements in your array:您可以轻松迭代数组中的所有元素:

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

Actually Java doesn't have multi-dimensional array in mathematical sense.实际上,Java 没有数学意义上的多维数组。 What Java has is just array of arrays, an array where each element is also an array. Java 所拥有的只是数组的数组,一个数组,其中每个元素也是一个数组。 That is why the absolute requirement to initialize it is the size of the first dimension.这就是为什么初始化它的绝对要求是第一维的大小。 If the rest are specified then it will create an array populated with default value.如果指定了其余部分,则它将创建一个填充有默认值的数组。

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

It also gives us a quirk.它也给了我们一个怪癖。 The size of the sub-array cannot be changed by adding more elements, but we can do so by assigning a new array of arbitrary size.子数组的大小不能通过添加更多元素来改变,但我们可以通过分配一个任意大小的新数组来实现。

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

If you want something that's dynamic and flexible (ie where you can add or remove columns and rows), you could try an "ArrayList of ArrayList":如果你想要动态和灵活的东西(即你可以添加或删除列和行的地方),你可以尝试“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);
    }
}

Output: Output:

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    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM