简体   繁体   中英

Are multi-dimensional arrays zero-inited?

The answer to this related question says one dimensional arrays are zero inited. From a small test I just ran, it seems multi-dimensional arrays are not zero inited . Any idea why?

The spec seems to specify that the init of a multi-dimensional array is equivalent to a set of single-dimensional array inits, in which case all the cells should have been zero inited.

The test I ran is equivalent to:

public class Foo {
  static int[][] arr;
  public static void bar() {
    arr = new int[20][20];

    // in the second run of Foo.bar(), the value of arr[1][1] is already 1
    // before executing the next statement!
    arr[1][1] = 1;
  }
}

Nope, multi-dimensional arrays are zero-initialized just fine:

public class Foo {
  static int[][] arr;
  public static void bar() {
    arr = new int[20][20];

    System.out.println("Before: " + arr[1][1]);
    // in the second run of Foo.bar(), the value of arr[1][1] is already 1
    // before executing the next statement!
    arr[1][1] = 1;
    System.out.println("After: " + arr[1][1]);
  }

  public static void main(String[] args) {
    bar();
    bar();
  }
}

Output:

Before: 0
After: 1
Before: 0
After: 1

If you still have doubts, find a similarly short but complete program which demonstrates the problem :)

Seems the problem is in the debugger or in the groovy runtime. We're talking about java code that is called from a groovy unit test in IntelliJ.

Take a look at this screenshot (check out the watch and the line the debugger is at):

在此处输入图片说明

 // in the second run of Foo.bar(), the value of arr[1][1] is already 1 // before executing the next statement! 

No it isn't. Show more of your code, When I run this:

public class Foo {
  public static void main(String[] args) throws Exception {
    bar();
    bar();
  }
  static int[][] arr;
  public static void bar() {
    arr = new int[20][20];
    System.out.println(arr[1][1]);
    arr[1][1] = 1;
  }
}

I get 0 twice.

It is a static array. So in the first call it will set arr[1][1] to 1

In the second call, just before the re-initialization takes places (before arr = new int[20][20]; ) before this line executed, the value will still be 1 .

If you are checking the value at that time then it is normal.

As you describe this only happens in the second call, this makes sense to me. It will continue to happen for all calls except the first one. :)

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