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

标签 java oop

众所周知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/

相关文章:

java - 使用 JOptionPane 时的小问题

java - 方法调用和发送已关闭

java - 数组索引越界

java - 从 3rd 方库中删除未使用的 Assets

c# - 业务层设计困境 : memory or IO?

php - 何时在 PHP 中使用静态修饰符

java - org.junit.Assert.assertThat 比 org.hamcrest.MatcherAssert.assertThat 好吗?

c++ - 如果类有 const 变量,为什么我能够将一个对象复制到另一个对象中?

javascript - 抛出错误消息无法在 OOP Javascript 三元运算符上编译

c# - 将int放入各种对象数组时得到 'NullReferenceException'