2015-07-12 75 views
4

下面代碼陣列零長度的在Java

public class Example { 
    static int[] member; 
    public static void main(String[] args) { 
     int[] ic = new int[0]; 
     if (ic == null){ 
      System.out.println("ic is null"); 
     } 
     System.out.println(ic); // [[email protected] 
     if(member == null){ 
      System.out.println("member is null"); 
     } 
    } 
} 

很明顯,元件不能零長度數組加入。

ic指的是什麼,如果ic不是null

根據下圖,指向內存位置659e0bfd(它是空的)是ic

enter image description here

回答

4

如果它不爲空,ic指向什麼?

它指向一個零容量的空數組。數組是引用類型,並像其他引用類型一樣爲它們分配內存空間。

+0

根據上述代碼在內存地址爲'659e0bfd'的空數組? – overexchange

+1

@proxchange爲數組輸出的哈希碼可能與內存地址有關,但它不是內存地址本身。請參閱http://stackoverflow.com/questions/2237720/what-is-an-objects-hash-code-if-hashcode-is-not-overridden –

+0

@overchange是'obj1 == obj2'檢查兩個變量參考內存中的同一個對象。 Java沒有獲取內存地址的機制。 – manouti

2

ic指爲空數組的實例。它不包含任何元素(ic[i]會爲i的每個值拋出ArrayIndexOutOfBoundsException),但它不爲空。

2

想象一個數組作爲一個盒子。你可以聲明一個容量爲3的盒子,比如3

int[] x = new int[3]; 

你會得到這個盒子:[_,_,_]。您可以填寫一些數字

x[1] = 9; 

得到[_,9,_]。你做了什麼,而是被宣告了零容量箱

int[] x = new int[0]; 

得到這個:[]。並猜測如果你嘗試向它添加一個元素會發生什麼?你不能。

因此,要回答你的問題,ic指向什麼?您的空(和零容量)框。