2012-12-31 35 views
5

可能重複:
Java - boolean primitive type - size程序來計算一個布爾變量的大小

我設計這個程序來計算在Java中boolean的大小。

public class BooleanSizeTest{ 
    /** 
    * This method attempts to calculate the size of a boolean. 
    */ 
    public static void main(String[] args){ 
     System.gc();//Request garbage collection so that any arbitrary objects are removed. 
     long a1, a2, a3;//The variables to hold the free memory at different times. 
     Runtime r = Runtime.getRuntime();//Get the runtime. 
     System.gc();//Request garbage collection so that any arbitrary objects are removed. 
     a1 = r.freeMemory();//The initial amount of free memory in bytes. 
     boolean[] lotsOfBools = new boolean[10_000_000];//Declare a boolean array. 
     a2 = r.freeMemory(); 
     System.gc();//Request garbage collection. 
     a3 = r.freeMemory();// Amount of free memory after creating 10,000,000 booleans. 
     System.out.println("a1 = "+a1+", a2 = "+a2+", a3 = "+a3); 
     double bSize = (double)(a1-a2)/10_000_000;/*Calculate the size of a boolean 
     using the difference of a1 and a2*/ 
     System.out.println("boolean = "+bSize); 
    } 
} 

當我運行該程序時,它說的大小是1.0000016字節。現在,Oracle Java文檔說boolean的大小爲「未定義」。 [見link]。 這是爲什麼呢?另外,boolean變量代表1位信息(truefalse),那麼剩下的7位會發生什麼?

回答

4

訪問1位是一個昂貴的操作;如果您從內存中檢索數據,則最有可能通過字或字節來完成。在Java中,布爾值的內部表示形式是一個實現細節,除非您正在執行虛擬機實施,否則您不應該擔心該實現細節。

+0

雖然一個布爾值可以重複爲1位值,但是這個規範不會強制VM實現者實際使用位域來實現它。 – gnlogic