5

重複の可能性:
Java - ブールプリミティブ型 - サイズ

booleanJavaで a のサイズを計算するようにこのプログラムを設計しました。

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 のドキュメントには、 a のサイズboolean「定義されていません」と記載されています。[リンクを参照]。これはなぜですか?また、boolean変数は 1 ビットの情報 (truefalse) を表すので、残りの 7 ビットはどうなるでしょうか。

4

1 に答える 1

4

1 ビットへのアクセスはコストのかかる操作です。メモリからデータを取得する場合、ワード単位またはバイト単位で行う可能性が最も高くなります。Java では、ブール値の内部表現は実装の詳細であり、VM 実装を行っていない限り気にする必要はありません。

于 2012-12-31T14:56:23.317 に答える