java如何在引擎盖下实现字符串的flyweight模式? [英] How does java implement flyweight pattern for string under the hood?
问题描述
如果您有两个String的实例,并且它们相等,那么在Java中它们将共享相同的内存。这是如何实现的?
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?
编辑:我的应用程序使用大量的String对象,其中许多是相同的。使用Java String常量池的最佳方法是什么,以避免创建自定义flyweight实现?
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?
推荐答案
源代码 java.lang.String
(整个java api的源代码是JDK的一部分)。
Look at the source code of java.lang.String
(the source for entire java api is part of the JDK).
总结一下:String包裹一个 char []
的子序列。从来没有修改过 char []
的支持。这是通过在 String
类之外没有泄漏或捕获这个 char []
来实现的。但是,几个 Strings
可以共享相同的 char []
(请参阅 String.substring的实现
)。
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.
这篇关于java如何在引擎盖下实现字符串的flyweight模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!