吊打面试官,聊聊:Java中String对象的大小?(史上最全)

下面是一个常见的Java 面试题:

聊聊:Java中String对象的大小?

首先,看看空String占用的空间

当前内存大小是在默认开启压缩指针的条件下

  • 对象头 12
  • char[]数组引用 4
  • int 类型 hash数据大小 4
  • loss due to the next object alignment 对齐填充 4
    总结:24

再次,来看看String类中的成员变量。

/** The value is used for character storage. */ 
private final char value[];

/** Cache the hash code for the string */ 
private int hash; // Default to 0

/** use serialVersionUID from JDK 1.0.2 for interoperability */ 
private static final long serialVersionUID = -6849794470754667710L;

非空String占用的空间

当前内存大小是在默认开启压缩指针的条件下

  • 对象头 12
  • char[]数组引用 4
  • int 类型 hash数据大小 4
  • loss due to the next object alignment 对齐填充 4
    总结:24

推荐阅读:

猜你喜欢

转载自blog.csdn.net/crazymakercircle/article/details/128258374