实习生如何在以下代码中工作? [英] How does intern work in the following code?
问题描述
String a = "abc";
String b = a.substring(1);
b.intern();
String c = "bc";
System.out.println(b == c);
问题可能是愚蠢的,因为实习生在这里没有主要用法,但我对这个事实感到困惑,为什么 b == c
结果 true
。
The question might be foolish as intern has no major usage here, still I am confused about the fact, why does b == c
results true
.
当
String b = a.substring(1)
执行,String b
对具有bc的对象的引用
is executed, String b
references to object having "bc"
b.intern
创建文字bc
在字符串常量池中,即使它,如何 b == c
结果 true
?
Does b.intern
create the literal "bc"
in String Constant pool, even if it does, how come b==c
result in true
?
推荐答案
字符串b = a.substring(1);
返回字符串实例包含bc
,但此实例不是字符串池的一部分(默认情况下只有文字被插入,字符串是通过 new String(data)创建的
并从 substring
或 nextLine
等方法返回,默认情况下不会被实习。
String b = a.substring(1);
returns string instance which contains "bc"
but this instance is not part of string pool (only literals are by defaults interned, string created via new String(data)
and returned from methods like substring
or nextLine
are not interned by default).
现在当你调用
b.intern();
此方法检查字符串池是否包含等于存储在 b <1的字符串/ code>(即bc)如果没有,则将该字符串放在那里。所以正常情况下,池中没有代表
bc
的字符串,它会在 b
处放置字符串。
this method checks if String Pool contains string equal to one stored in b
(which is "bc") and if not, it places that string there. So sine there is no string representing "bc"
in pool it will place string from b
there.
所以现在字符串池包含abc
和bc
。
So now String pool contains "abc"
and "bc"
.
因此,当你打电话时
String c = "bc";
字符串文字代表 bc
(这是相同的)如在 b
引用中)将从池中重复使用,这意味着 b
和 c
将保存相同的实例。
string literal representing bc
(which is same as in b
reference) will be reused from pool which means that b
and c
will hold same instance.
这确认 b == c
的结果,返回 true
。
这篇关于实习生如何在以下代码中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!