关于Java的字符串池的问题 [英] Questions about Java's String pool
问题描述
考虑以下代码:
String first = "abc";
String second = new String("abc");
当使用 new
关键字时,Java将再次创建 abc
字符串
吧?
这会存储在常规堆还是 String
池中?
多少 String
s将以 String
池结尾?
When using the new
keyword, Java will create the abc
String
again right?
Will this be stored on the regular heap or the String
pool?
How many String
s will end in the String
pool?
推荐答案
如果你使用 new
关键字,新的字符串
将创建对象。请注意,对象始终位于堆上 - 字符串池不是与堆分开的单独内存区域。
If you use the new
keyword, a new String
object will be created. Note that objects are always on the heap - the string pool is not a separate memory area that is separate from the heap.
字符串池就像一个缓存。如果你这样做:
The string pool is like a cache. If you do this:
String s = "abc";
String p = "abc";
然后Java编译器足够聪明,只能生成一个 String
object, s
和 p
都将引用同一个String对象。如果你这样做:
then the Java compiler is smart enough to make just one String
object, and s
and p
will both be referring to that same String object. If you do this:
String s = new String("abc");
然后会有一个 String
对象池,代表文字abc
的池,并且会有一个单独的 String
对象,而不是池,包含池对象内容的副本。由于 String
在Java中是不可变的,所以你不会通过这样做获得任何东西;调用 new String(literal)
在Java中永远不会有意义并且效率不必要。
then there will be one String
object in the pool, the one that represents the literal "abc"
, and there will be a separate String
object, not in the pool, that contains a copy of the content of the pooled object. Since String
is immutable in Java, you're not gaining anything by doing this; calling new String("literal")
never makes sense in Java and is unnecessarily inefficient.
请注意,你可以在 String
对象上调用 intern()
。这将把 String
对象放入池中(如果它尚不存在),并返回对池化字符串的引用。 (如果它已经在池中,它只返回对已存在的对象的引用)。有关详细信息,请参阅该方法的API文档。
Note that you can call intern()
on a String
object. This will put the String
object in the pool if it is not already there, and return the reference to the pooled string. (If it was already in the pool, it just returns a reference to the object that was already there). See the API documentation for that method for more info.
另请参阅字符串实习(维基百科)。
See also String interning (Wikipedia).
这篇关于关于Java的字符串池的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!