对这个相关问题的回答说一维数组是零初始化的。从我刚刚进行的一次小测试来看,多维数组似乎不是零初始化的。知道为什么吗?
规范似乎指定了多维数组的初始化等同于一组一维数组的初始化,在这种情况下,所有单元格都应该被初始化为零。
我运行的测试等同于:
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)
不,多维数组可以零初始化:
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)
如果您仍然有疑问,请找到一个类似的简短但完整的程序来演示问题:)
| 归档时间: |
|
| 查看次数: |
733 次 |
| 最近记录: |