简体   繁体   English

在JAVA中初始化2D数组

[英]initializing a 2d array in JAVA

If I declare a 2d array, for example: 如果我声明一个二维数组,例如:

int[][] numbers = new int[5][];

I thought that you had to individually declare/initialize each of the 5 int[]? 我以为您必须分别声明/初始化5个int []? For example, before I assign a value to numbers[0][1], I would have to say: 例如,在为数字[0] [1]分配值之前,我必须说:

numbers[0] = new int[4];

I wrote a small program and explicitly put a value in numbers[0][1], ran it, and it worked without initializing numbers[0] first. 我编写了一个小程序,将一个值显式地放入了numbers [0] [1]中,然后运行它,并且它无需先初始化numbers [0]就可以正常工作。 Am I completely off thinking that the individual arrays have to be initialized first in a 2d array? 我是否完全不认为必须先在2d数组中初始化各个数组?

Edit: My misunderstanding was in the initialization. 编辑:我的误解是在初始化。 The 1st 2 statements are ok, because I declared the length of each int[] in goodArray to be 3, which causes all of them to be initialized. 第1条2条语句是可以的,因为我声明了goodArray中每个int []的长度为3,这导致它们全部被初始化。 Whereas in the badArray declaration, I only declared how many arrays there were(3), so I get a npe: 而在badArray声明中,我只声明了有多少个数组(3),所以我得到了一个npe:

int [][]goodArray = new int[3][3];
goodArray[0][1] = 2;

int[][] badArray = new int[3][];
badArray[0][0] = 2;

使用Java中的多维数组,您可以指定位置,而无需单独定义它们。

You can easily test the behavior of the 2D arrays using examples like the one below: 您可以使用以下示例轻松地测试2D阵列的行为:

int[][] numbers1 = new int[][] { {1, 2, 3}, {1, 2, 3, 4, 5}}; /* full initialization */
numbers1 = new int[3][]; /* [3][0] is null by default */
try {
  System.out.println(numbers1[0][0]);
} catch (NullPointerException e) {
  System.out.println(e);
}
numbers1[0] = new int[3]; /* all three ints are initialized to zero by default */
System.out.println(numbers1[0][0]);
numbers1[0] = new int[] {1, 2, 3};
System.out.println(numbers1[0][0]);

Will produce the following output: 将产生以下输出:

java.lang.NullPointerException
0
1

int[][] numbers = new int[5][]; int [] []个数字=新的int [5] [];

With the previous line you have created 5 int[] one dimensional array. 在上一行中,您创建了5个int []一维数组。 Now you need to say the size for each one dimension array before you use them. 现在,在使用它们之前,需要说出每个一维数组的大小。 Java gives this flexibility ao that you can have variable size one dimensional int [] arrays inside 2D array. Java提供了这种灵活性,您可以在2D数组中拥有可变大小的一维int []数组。

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

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