【发布时间】:2022-11-20 12:28:54
【问题描述】:
I am currently doing some work with a 2D array of objects. The 2D array is initialised as such:
Object[][] twoDarray = new Object[3][5];
After initialisation, I then populate the array with a nested for loop:
for (int x = 0; x < twoDarray.length; x++) {
for (int y = 0; y < twoDarray[x].length; y++) {
twoDarray[x][y] = new Object();
}
}
Now, from my understanding, every index in the array should be populated with an Object. However, when I print the contents of the array out, I get 15 objects and 15 'null' instances. I thought this array would have [3]*[5] indexes. Another weird behaviour that I do not understand is if I run the code:
System.out.println(twoDarray[0][4]);
it prints one value which is an instance of an object, and another value underneath which is null. Either something is going wrong, or I just completely misunderstand 2D arrays. Any help would be much appreciated, thanks in advance.
【问题讨论】:
-
Please show the full code.
-
"when I print the contents of the array out, I get 15 objects and 15 'null' instances." Please show the code that does this.
-
@Code-Apprentice it's the same as the initialisation for loops but instead of populating each index I just print it
-
@pythonoob You need to show it, not describe it. The code you give here does not do what you say it does. From your description, I can easily write code that behaves correctly. But that won't help you solve the problem with your code because it will be completely different than what you have. Please provide a minimal reproducible example along with the output. This should be code that we can copy/paste and run ourselves and get the same output you do.
-
Running the code you provided, I only get one output, which is expected since there is only one call for
System.out.prinln(). That means you are not providing everything to reproduce the behavior you describe. paiza.io/projects/UkuhJIBgx_07gymEf14D7Q
标签: java