Java中字符串实习的奇怪行为 [英] Strange behavior with string interning in Java

查看:74
本文介绍了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. 字符串文字1(传入 String 构造函数)在地址 A 实习。

    String s1 在地址 B 处创建,因为它不是文字或常量表达式。

  2. 对<$ c $的调用c> intern()无效。字符串1已经被实习,并且操作结果未分配回 s1

  3. 字符串 s2 ,值为1从字符串池中检索,所以分解决 A

  1. The string literal "1" (passed into the String constructor) is interned at address A.
    String s1 is created at address B because it is not a literal or constant expression.
  2. The call to intern() has no effect. String "1" is already interned, and the result of the operation is not assigned back to s1.
  3. 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";




  1. 字符串 s3 在地址 C 创建。

  2. intern()的调用添加值为<的字符串11地址 C 到字符串池。

  3. 字符串 s4 值为从字符串池中检索11,因此指向地址 C

  1. String s3 is created at address C.
  2. The call to intern() adds the string with value "11" at address C to the string pool.
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆