有人能告诉我在Java中,boolean类型的位数是多少吗?
这取决于虚拟机,但可以轻松地从一个关于Java字节的类似问题中的代码进行适应:
class LotsOfBooleans
{
boolean a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af;
boolean b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf;
boolean c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf;
boolean d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df;
boolean e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef;
}
class LotsOfInts
{
int a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af;
int b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf;
int c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf;
int d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df;
int e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef;
}
public class Test
{
private static final int SIZE = 1000000;
public static void main(String[] args) throws Exception
{
LotsOfBooleans[] first = new LotsOfBooleans[SIZE];
LotsOfInts[] second = new LotsOfInts[SIZE];
System.gc();
long startMem = getMemory();
for (int i=0; i < SIZE; i++)
{
first[i] = new LotsOfBooleans();
}
System.gc();
long endMem = getMemory();
System.out.println ("Size for LotsOfBooleans: " + (endMem-startMem));
System.out.println ("Average size: " + ((endMem-startMem) / ((double)SIZE)));
System.gc();
startMem = getMemory();
for (int i=0; i < SIZE; i++)
{
second[i] = new LotsOfInts();
}
System.gc();
endMem = getMemory();
System.out.println ("Size for LotsOfInts: " + (endMem-startMem));
System.out.println ("Average size: " + ((endMem-startMem) / ((double)SIZE)));
// Make sure nothing gets collected
long total = 0;
for (int i=0; i < SIZE; i++)
{
total += (first[i].a0 ? 1 : 0) + second[i].a0;
}
System.out.println(total);
}
private static long getMemory()
{
Runtime runtime = Runtime.getRuntime();
return runtime.totalMemory() - runtime.freeMemory();
}
}
再次强调,这取决于虚拟机,但在我运行Sun的JDK版本1.6.0_11的Windows笔记本电脑上,我获得了以下结果:
Size for LotsOfBooleans: 87978576
Average size: 87.978576
Size for LotsOfInts: 328000000
Average size: 328.0
这表明Sun的JVM基本上可以将布尔值打包成每个字节。
这取决于虚拟机。
顺带一提...
如果您考虑使用布尔对象数组,请不要这样做。相反,使用BitSet - 它具有一些性能优化(和一些很好的附加方法,允许您获取下一个设置/未设置的位)。
我读到Java为boolean
数据类型保留了一个字节,但实际上只使用了一位(bit)。然而,文档中说“它的‘大小’并没有被精确定义”。请参见此处。
boolean
值在JVM中被编译为int
数据类型。点击这里查看更多信息。
Java中的布尔类型大小取决于虚拟机。 但是,任何Java对象都会按照8字节的粒度对齐。一个布尔类型有8字节的头部和1字节的有效负载,总共占用9字节的空间。JVM会将其向上舍入到下一个8的倍数。 因此,java.lang.Boolean的一个实例占用16字节内存。
它是未定义的;像Jon Skeet建议的那样做会在给定平台上得到一个近似值,但要精确地了解特定平台的情况,最好使用分析器。