多维数组是零初始化的吗?

rip*_*234 0 java

对这个相关问题的回答说一维数组是零初始化的。从我刚刚进行的一次小测试来看,多维数组似乎不是零初始化的。知道为什么吗?

规范似乎指定了多维数组的初始化等同于一组一维数组的初始化,在这种情况下,所有单元格都应该被初始化为零。

我运行的测试等同于:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

不,多维数组可以零初始化:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Before: 0
After: 1
Before: 0
After: 1
Run Code Online (Sandbox Code Playgroud)

如果您仍然有疑问,请找到一个类似的简短但完整的程序来演示问题:)

  • 我正准备粘贴类似的代码段,以便找到您的代码段。您的睡眠时间表是什么?(这样,当您起床时,我几乎可以停止尝试) (2认同)
  • @shadowfoxml:参见http://meta.stackexchange.com/questions/555/why-does-jon-skeet-never-sleep (2认同)