gpt4 book ai didi

java - java中对象的大小是多少

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

众所周知java使用了以下几种数据类型

byte    Occupy 8 bits in memory
short Occupy 16 bits in memory
int Occupy 32 bits in memory
long Occupy 64 bits in memory

如果我创建一个类

class Demo{
byte b;
int i;
long l;
}

Demo obj = new Demo();

现在我的问题是obj大小是 < or > or = b+i+l 的大小这是 104 bytes .请给我澄清并附上适当的理由。

谢谢,
阿尼尔·库马尔 C

最佳答案

来自 http://www.javamex.com/tutorials/memory/object_memory_usage.shtml

  1. a bare Object takes up 8 bytes;
  2. an instance of a class with a single boolean field takes up 16 bytes: 8 bytes of header, 1 byte for the boolean and 7 bytes of "padding" to make the size up to a multiple of 8;
  3. an instance with eight boolean fields will also take up 16 bytes: 8 for the header, 8 for the booleans; since this is already a multiple of 8, no padding is needed;
  4. an object with a two long fields, three int fields and a boolean will take up:
    • 8 bytes for the header;
    • 16 bytes for the 2 longs (8 each);
    • 12 bytes for the 3 ints (4 each);
    • 1 byte for the boolean;
    • a further 3 bytes of padding, to round the total up from 37 to 40, a multiple of 8.

关于java - java中对象的大小是多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10549381/

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