Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用于计算布尔变量大小的程序_Java_Boolean_Primitive Types - Fatal编程技术网

Java 用于计算布尔变量大小的程序

Java 用于计算布尔变量大小的程序,java,boolean,primitive-types,Java,Boolean,Primitive Types,可能重复: 我设计了这个程序来计算Java中布尔值的大小 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 arbit

可能重复:

我设计了这个程序来计算Java中
布尔值的大小

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
变量表示1位信息(
true
false
),因此剩余的7位会发生什么情况?

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

令人满意的是,尽管布尔值可以表示为1位值,但规范并不强制VM实现者使用位字段实现它。