问题描述
让我们看一下以下代码片段:
Let's look at the folloing code snippet:
String s1 = "Hello";
String s2 = "Hello";
由于实习,两个变量都引用同一个对象。由于字符串是不可变的,因此只创建一个对象并且都引用同一个对象。
Both variables refer to the same object due to interning. Since strings are immutable, only one object is created and both refer to the same object.
A 常量池
是还有一些东西,它包含在类中声明的所有常量(整数,字符串等)。它特定于每个类。
A constant pool
is also something, which holds all the constants (integer, string, etc.) that are declared in a class. It is specific to each class.
System.out.println("Hello"); // I believe this Hello is different from above.
问题:
-
字符串池
是否引用常量池中常量字符串对象的池? - 如果是, String pool 在整个应用程序中是通用的还是特定于类?
- Does
string pool
refer to the pool of a constant string object in the constant pool? - If yes, is String pool common throughout the whole application or specific to a class?
推荐答案
- 字符串池是指常量池常量池中的字符串对象?
否。
常量池是指类文件中特殊格式的字节集合,对Java类加载器有意义。其中的字符串是,它们不是Java对象。还有很多种常量,而不仅仅是字符串。
"Constant pool" refers to a specially formatted collection of bytes in a class file that has meaning to the Java class loader. The "strings" in it are serialized, they are not Java objects. There are also many kinds of constants, not just strings in it.
参见
相比之下,字符串池在运行时使用(不仅仅在类加载期间),仅包含字符串,字符串池中的字符串是java对象。
字符串池是一个线程安全的弱映射,从 java.lang.String
实例到 java.lang.String
用于实习字符串的实例。
In contrast, the "String pool" is used at runtime (not just during class loading), contains only strings, and the "strings" in the string pool are java objects.The "string pool" is a thread-safe weak-map from java.lang.String
instances to java.lang.String
instances used to intern strings.
说
此外,字符串文字总是指相同的实例class String
。这是因为字符串文字 - 或者更常见的是作为常量表达式(第15.28节)的值的字符串 - 被实现以便使用方法 String.intern 。
Moreover, a string literal always refers to the same instance of class
String
. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern
.
这篇关于字符串池与常量池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!