【发布时间】:2012-08-14 02:52:51
【问题描述】:
我正在查看 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
[...]
}
但我知道 Java 对字符串使用引用和池,以避免重复。我天真地期待一个 pimpl 成语,其中 String 实际上只是一个 impl 的引用。到目前为止我还没有看到。有人可以解释如果我放一个 String x,Java 将如何知道使用引用吗?我的一门课的成员?
附录:这可能是错误的,但如果我处于 32 位模式,我应该计算:4 个字节用于引用“value[]”,4 个字节用于偏移量,4 个字节用于计数,4 用于所有实例的哈希值类字符串?这意味着写“String x;”在我的一个班级中,我的班级的“权重”自动增加了至少 32 个字节(我可能在这里错了)。
【问题讨论】:
-
字符串就是字符串。它是否被池化对字符串的性质没有影响,只对它的存储位置和可以围绕它进行的优化。
-
pimpl 成语?我的猜测是您来自 C++ 背景,并且您没有意识到 Java 的对象模型与 C++ 的不同。 Java 不仅仅是拼写错误的 C++,它是一种非常不同的语言。我强烈建议您阅读 Java Language Specification 以更详细地了解 Java 是什么样的。
-
猜得好!我是一个 C++ 人。我对 Java 有一些经验,但我觉得这很令人不安。
标签: java string size primitive-types