Java字符串实习生和文字 [英] Java string intern and literal

查看:76
本文介绍了Java字符串实习生和文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的两段代码是否相同?

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 this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String 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屋!

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