Java中字符串实习的奇怪行为 [英] Strange behavior with string interning in Java
问题描述
代码如下:
String s = new String("1");
s.intern();
String s2 = "1";
System.out.println(s == s2);
String s3 = new String("1")+new String("1");
s3.intern();
String s4 = "11";
System.out.println(s3 == s4);
上述代码的输出为:
false
true
我知道 s
和 s2
是不同的对象,因此结果的计算结果为false,但第二个结果的计算结果为true。谁能告诉我差异?
I know that s
and s2
are different objects, so the result evaluates to false, but the second result evaluates to true. Can anyone tell me the difference?
推荐答案
以下是发生的事情:
String s1 = new String("1");
s1.intern();
String s2 = "1";
- 字符串文字
1
(传入String
构造函数)在地址 A 实习。
Strings1
在地址 B 处创建,因为它不是文字或常量表达式。 - 对<$ c $的调用c> intern()无效。字符串
1
已经被实习,并且操作结果未分配回s1
。 - 字符串
s2
,值为1
从字符串池中检索,所以分解决 A 。
- The string literal
"1"
(passed into theString
constructor) is interned at address A.
Strings1
is created at address B because it is not a literal or constant expression. - The call to
intern()
has no effect. String"1"
is already interned, and the result of the operation is not assigned back tos1
. - String
s2
with value"1"
is retrieved from the string pool, so points to address A.
结果:字符串 s1
和 s2
指向不同的地址。
Result: Strings s1
and s2
point to different addresses.
String s3 = new String("1") + new String("1");
s3.intern();
String s4 = "11";
- 字符串
s3
在地址 C 创建。 - 对
intern()
的调用添加值为<的字符串11
地址 C 到字符串池。 - 字符串
s4
值为从字符串池中检索11
,因此指向地址 C 。
- String
s3
is created at address C. - The call to
intern()
adds the string with value"11"
at address C to the string pool. - String
s4
with value"11"
is retrieved from the string pool, so points to address C.
结果:字符串 s3
和 s4
指向相同的地址。
Result: Strings s3
and s4
point to the same address.
字符串1
在调用 intern()
之前被实习由于它存在于 s1 = new String(1)
构造函数调用中而生成。
String "1"
is interned before the call to intern()
is made, by virtue of its presence in the s1 = new String("1")
constructor call.
将构造函数调用更改为 s1 = new String(new char [] {'1'})
将使 s1 == s2
的比较为true,因为现在两者都将通过调用 s1.intern()来引用显式实例化的字符串
。
Changing that constructor call to s1 = new String(new char[]{'1'})
will make the comparison of s1 == s2
evaluate to true because both will now refer to the string that was explicitly interned by calling s1.intern()
.
(我使用了中的代码这个答案获取有关字符串内存位置的信息。)
(I used the code from this answer to get information about the strings' memory locations.)
这篇关于Java中字符串实习的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!