繁体   English   中英

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

[英]Are multi-dimensional arrays zero-inited?

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

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

我运行的测试等同于:

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;
  }
}

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

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();
  }
}

输出:

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

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

似乎问题出在调试器或groovy运行时中。 我们正在谈论从IntelliJ中的常规单元测试调用的Java代码。

看一下此屏幕截图(查看手表和调试器所在的行):

在此处输入图片说明

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

不,不是。 显示更多您的代码,当我运行此代码时:

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;
  }
}

我两次得到0。

它是一个静态数组。 因此,在第一个调用中,它将把arr [1] [1]设置为1

在第二个调用中,在before this line executed, the value will still be 1之前,刚好在进行初始化之前(在arr = new int[20][20]; before this line executed, the value will still be 1before this line executed, the value will still be 1

如果您当时正在检查该值,那是正常的。

正如您所描述的,这仅在第二次通话中发生,这对我来说很有意义。 除第一个呼叫外,所有呼叫将继续发生。 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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