多维数组是否为零?

这个相关问题的答案是一维数组是零。 从我刚刚运行的一个小测试来看,似乎多维数组不是零 。 知道为什么吗?

规范似乎指出多维数组的init等同于一组一维数组的内部,在这种情况下,所有单元应该是零。

我跑的测试相当于:

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 

如果你还有疑问,找一个同样简短但完整的程序来certificate问题:)

似乎问题出在调试器或groovy运行时中。 我们讨论的是从IntelliJ中的groovyunit testing中调用的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

在第二次调用中,就在重新初始化之前(在arr = new int[20][20]; before this line executed, the value will still be 1before this line executed, the value will still be 1

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

正如你所描述的那样,这只发生在第二次调用中,这对我来说很有意义。 对于除第一个之外的所有呼叫,它将继续发生。 🙂