2011-02-14 16 views
0

對此related question的答案表示一維數組是零引用的。從我剛跑過的一個小測試看來,似乎多維數組並不是零引力。任何想法爲什麼?多維數組是否爲零?

The spec似乎指定多維數組的初始值等於一組一維數組inits,在這種情況下,所有單元應該已經被零點定位。

我跑的測試等同於:

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

你如何檢查值?無論你運行多少次,我都會看到它總是返回0。 – fmucar 2011-02-14 16:21:37

+0

@fmucar - 這是一個調試器問題 - 請參閱我發佈的答案以獲取更多詳細信息。 – ripper234 2011-02-14 16:36:14

+0

請參閱下面的答案。 – fmucar 2011-02-14 16:53:36

回答

4

不,多維數組初始化爲零就好:

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 

如果您仍然有疑問,找到一個類似的簡短但完整的程序來演示問題:)

0
// 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兩次。

1

看來問題是在調試器或在常規運行時。 我們正在討論從IntelliJ中的groovy單元測試中調用的java代碼。

看看這張截圖(看看手錶和線調試器是AT):

enter image description here

0

這是一個靜態數組。 所以在第一次調用它將設置改編[1] [1] 1

在第二次調用,只需重新初始化之前發生的地方(前arr = new int[20][20];before this line executed, the value will still be 1

如果要檢查當時的值,那麼這是正常的。

你描述這只是發生在第二個電話,這對我來說很有意義。除第一個呼叫外,它將繼續發生。 :)