问题描述
如果您有两个字符串实例,并且它们是平等的,则在Java中,它们将共享相同的内存.这是如何在引擎盖下实施的?
编辑:我的应用程序使用了大量的字符串对象,其中许多对象是相同的.使用Java String Constant Pool的最佳方法是什么?
推荐答案
查看java.lang.String的源代码(整个Java API的源是JDK的一部分).
总结:一个字符串包裹char[]的子序列.该备份char[]永远不会修改.这是通过在String类之外泄漏也没有捕获此char[]来完成的.但是,几个Strings可以共享相同的char[](请参阅String.substring的实现).
如其他答案中所述,也有实习的机制.
其他推荐答案
如果您有两个字符串的实例,并且它们是平等的,则在Java中,它们将共享相同的内存
这实际上不是100%true.
此博客是一个不错的说明为什么这样做,以及字符串常数池是什么.
其他推荐答案
字符串文字在Java中实施,因此实际上只有一个具有多个引用的字符串对象(当它们相等时,并非总是如此).请参阅java.net文章 all oridation()有关更多详细信息.
3.10.5字符串文字 jls谈论何时实习弦和何时不同.
问题描述
If you have two instances of a String, and they are equal, in Java they will share the same memory. How is this implemented under the hood?
EDIT: My application uses a large number of String objects, many of which are identical. What is the best way to make use of Java String constant pool, as to avoid creating custom flyweight implementation?
推荐答案
Look at the source code of java.lang.String (the source for entire java api is part of the JDK).
To summarize: A String wraps a subsequence of a char[]. That backing char[] is never modified. This is accomplished by neither leaking nor capturing this char[] outside the String class. However, several Strings can share the same char[] (see Implementation of String.substring).
There is also the mechanism of interning, as explained in the other answers.
其他推荐答案
If you have two instances of a String, and they are equal, in Java they will share the same memory
This is actually not 100% true.
This blog post is a decent explanation of why this is so, and what the String constant pool is.
其他推荐答案
String literals are interned in Java, so there's really only one String object with multiple references (when they are equal, which is not always the case). See the java.net article All about intern() for more details.
There's also a good example/explanation in section 3.10.5 String Literals of the JLS that talks about when Strings are interned and when they'll be distinct.