Java字符串实习生和文字 [英] Java string intern and literal
问题描述
下面的两段代码是否相同?
Are the below two pieces of code the same?
String foo = "foo";
String foo = new String("foo").intern();
推荐答案
它们具有相同的最终结果,但它们并不相同(它们将产生不同的字节码; new String("foo").intern()
版本实际上经过了这些步骤,生成了一个新的字符串对象,然后进行了实习).
They have the same end result, but they are not the same (they'll produce different bytecode; the new String("foo").intern()
version actually goes through those steps, producing a new string object, then interning it).
String#intern
中的两个相关引号:
当调用
intern
方法时,如果池已经包含与方法确定的等于此 String
对象的字符串,则返回池中的字符串.否则,将此String
对象添加到池中,并返回对该String
对象的引用.
When the
intern
method is invoked, if the pool already contains a string equal to thisString
object as determined by theequals(Object)
method, then the string from the pool is returned. Otherwise, thisString
object is added to the pool and a reference to thisString
object is returned.
所有文字字符串和字符串值常量表达式都将被插入.
All literal strings and string-valued constant expressions are interned.
所以最终结果是相同的:引用了内部字符串"foo"的变量.
So the end result is the same: A variable referencing the interned string "foo".
这篇关于Java字符串实习生和文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!