【问题标题】:Program to calculate the size of a boolean variable [duplicate]计算布尔变量大小的程序[重复]
【发布时间】:2012-12-15 16:30:19
【问题描述】:

可能重复:
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 位会发生什么?

【问题讨论】:

    标签: java boolean primitive-types


    【解决方案1】:

    访问 1 位是一项昂贵的操作;如果您从内存中检索数据,您最有可能按字或按字节进行。在 Java 中,布尔值的内部表示是一个实现细节,除非您正在执行 VM 实现,否则您不应该关心它。

    【讨论】:

    • 不错,虽然布尔值可以表示为 1 位值,但规范并不强制 VM 实现者使用位域来实际实现它。
    猜你喜欢
    • 1970-01-01
    • 2021-08-02
    • 2020-08-22
    • 2016-04-02
    • 2012-07-18
    • 2010-09-27
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多