栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java中布尔变量的大小是多少?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java中布尔变量的大小是多少?

它取决于虚拟机,但是很容易将代码从类似的问题改编成关于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();    }}

重申一下,这取决于VM,但是在运行Sun的

JDK build 1.6.0_11
的Windows笔记本电脑上,我得到以下结果:

Size for LotsOfBooleans: 87978576Average size: 87.978576Size for LotsOfInts: 328000000Average size: 328.0

这表明,Sun的JVM基本上可以将布尔值打包成一个字节。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/441809.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号