字符串池与concat一起使用时的行为有所不同? [英] String Pool behaves differently when used with concat?

查看:146
本文介绍了字符串池与concat一起使用时的行为有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String s1 = "Hello".concat("World");
String s3 = new String("HelloWorld"); //Line-2
String s2 = s1.intern();
System.out.println(s1 == s2); //false
System.out.println(s1 == s3); //false
System.out.println(s2 == s3); //false

如果我删除了Line-2并比较了s1 == s2,它将返回true。谁能解释一下Line-2之后字符串池中到底发生了什么?堆中和每个池中的每一行都发生了什么?

If I removed Line-2 and compare s1==s2, it will return true. Could anyone explain me what exactly happens in string pool after Line-2? And whats happening in each line in heap and in constant pool ?

根据我的理解,s1将在常量池中创建HelloWorld。
但是s1 == s2仍然是假的?

From what i understand s1 will create "HelloWorld" in constant pool. But still s1 == s2 is false ?

推荐答案

当你有这个:

String s1 = "Hello".concat("World");
String s2 = s1.intern();
System.out.println(s1 == s2); //true

... s1.intern() s1 添加到池中并返回 s1 ,因为池中已经没有等效的字符串。所以自然 s1 == s2 是真的。

...s1.intern() adds s1 to the pool and returns s1, because there's no equivalent string already in the pool. So naturally s1 == s2 is true.

但是如果你有这个:

String s1 = "Hello".concat("World");
String s3 = new String("HelloWorld"); //Line-2
String s2 = s1.intern();
System.out.println(s1 == s2); //false
System.out.println(s1 == s3); //false
System.out.println(s2 == s3); //false

... 已经 a HelloWorld该代码运行之前池中的字符串(因为在类加载期间将字符串文字放入池中)。所以调用 s1.intern()会从池中返回字符串,而不是 s1 。所以 s1 == s2 是假的。

...there's already a "HelloWorld" string in the pool before that code runs (because string literals are put in the pool during class loading). So calling s1.intern() returns the string from the pool, not s1. So s1 == s2 is false.

如果我们这样做,这是更明显的:

This is more obvious if we do this:

String s1 = "Hello".concat("World");
String sx = "HelloWorld";
String s3 = new String(sx);
String s2 = s1.intern();
System.out.println(s1 == s2); //false
System.out.println(s1 == s3); //false
System.out.println(s2 == s3); //false
System.out.println(s1 == sx); //false
System.out.println(s2 == sx); //true

sx 是中的一个代码开始运行之前的池。

sx is the one in the pool before the code starts running.


根据我的理解,s1将在常量池中创建HelloWorld

From what i understand s1 will create "HelloWorld" in constant pool

不, concat 不会将其返回字符串放入池中。当您调用 s1.intern()时, s1 仅放入池以后 ,并且仅当池中没有等效字符串时。没有代码中没有Line-2的情况,但代码中有Line-2时:HelloWorld该字面上的文字。

No, concat doesn't put its return string in the pool. s1 is only put in the pool later, when you call s1.intern(), and only if there isn't already an equivalent string in the pool. There isn't when you don't have "Line-2" in the code, but there is when "Line-2" is in the code: The "HelloWorld" literal on that line.

这篇关于字符串池与concat一起使用时的行为有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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