gpt4 book ai didi

java - 计算 boolean 变量大小的程序

转载 作者:搜寻专家 更新时间:2023-10-31 20:13:37 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
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 位会怎样?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com