简体   繁体   中英

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[]? For example, before I assign a value to numbers[0][1], I would have to say:

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. Am I completely off thinking that the individual arrays have to be initialized first in a 2d array?

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. Whereas in the badArray declaration, I only declared how many arrays there were(3), so I get a 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:

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

With the previous line you have created 5 int[] one dimensional array. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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