【问题标题】:2D array having double the expected amount of indexes2D array having double the expected amount of indexes
【发布时间】: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


【解决方案1】:

There is nothing wrong with your code. You can verify your 2D array with the following sn-p:

for (var x : twoDarray) {
    for (var y : x) {
        System.out.println(y);
    }
}

Which should give you something similar to this:

java.lang.Object@1c655221
java.lang.Object@ee7d9f1
java.lang.Object@15615099
java.lang.Object@1edf1c96
java.lang.Object@368102c8
java.lang.Object@6996db8
java.lang.Object@1963006a
java.lang.Object@7fbe847c
java.lang.Object@41975e01
java.lang.Object@c2e1f26
java.lang.Object@dcf3e99
java.lang.Object@6d9c638
java.lang.Object@7dc5e7b4
java.lang.Object@1ee0005
java.lang.Object@75a1cd57

From the sound of it, your problem is elsewhere.

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 1970-01-01
    • 2021-05-05
    • 2022-12-01
    • 2021-11-01
    • 2020-12-05
    • 2018-08-25
    • 2021-07-28
    • 2018-12-23
    相关资源
    最近更新 更多