Fra*_*ank 5 java string size primitive-types
我正在查看 String 的 openjdk 实现和私有的,每个实例成员看起来像:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
{
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
/** Cache the hash code for the string */
private int hash; // Default to 0
[...]
}
Run Code Online (Sandbox Code Playgroud)
但我知道 Java 对字符串使用引用和池,以避免重复。我天真地期待 pimpl 成语,其中 String 实际上只是对 impl 的引用。到目前为止我还没有看到。有人能解释一下,如果我放了一个字符串 x,Java 将如何知道使用引用吗?我的其中一个课程的成员?
附录:这可能是错误的,但如果我处于 32 位模式,我是否应该计算:4 个字节用于引用“value[]”,4 个字节用于偏移量,4 个字节用于计数,4 个用于哈希类 String 的所有实例? 那意味着写“String x;” 在我的一堂课中,我的班级的“权重”自动增加了至少 32 个字节(我可能在这里错了)。
Java总是使用对任何对象的引用。没有办法让它不使用引用。至于字符串池,这是由字符串文字的编译器在运行时通过调用String.intern. 很自然,大多数 的实现String都忽略了它是否正在处理常量池引用的实例。