[英]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 1
) before this line executed, the value will still be 1
。
如果您當時正在檢查該值,那是正常的。
正如您所描述的,這僅在第二次通話中發生,這對我來說很有意義。 除第一個呼叫外,所有呼叫將繼續發生。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.