我们什么时候应该在字符串文字上使用字符串的实习生方法 [英] When should we use intern method of String on String literals
问题描述
根据String#intern(), intern
方法应该从字符串池中返回字符串,如果字符串在字符串池中找到,否则将在字符串池中添加一个新的字符串对象和 this 的引用返回字符串.
According to String#intern(), intern
method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string object will be added in String pool and the reference of this String is returned.
所以我试过这个:
String s1 = "Rakesh";
String s2 = "Rakesh";
String s3 = "Rakesh".intern();
if ( s1 == s2 ){
System.out.println("s1 and s2 are same"); // 1.
}
if ( s1 == s3 ){
System.out.println("s1 and s3 are same" ); // 2.
}
我原以为 s1 和 s3 相同
将在 s3 被实习时打印,而 s1 和 s2 相同
将不会打印.但结果是:两行都被打印出来.所以这意味着,默认情况下字符串常量是实习的.但如果是这样,那我们为什么需要 intern
方法呢?换句话说,我们什么时候应该使用这种方法?
I was expecting that s1 and s3 are same
will be printed as s3 is interned, and s1 and s2 are same
will not be printed. But the result is: both lines are printed. So that means, by default String constants are interned. But if it is so, then why do we need the intern
method? In other words when should we use this method?
推荐答案
Java 自动实习字符串文字.这意味着在许多情况下,== 运算符似乎对字符串的作用与对整数或其他原始值的作用相同.
Java automatically interns String literals. This means that in many cases, the == operator appears to work for Strings in the same way that it does for ints or other primitive values.
由于字符串文字的实习是自动的,intern()
方法将用于用 new String()
Since interning is automatic for String literals, the intern()
method is to be used on Strings constructed with new String()
使用您的示例:
String s1 = "Rakesh";
String s2 = "Rakesh";
String s3 = "Rakesh".intern();
String s4 = new String("Rakesh");
String s5 = new String("Rakesh").intern();
if ( s1 == s2 ){
System.out.println("s1 and s2 are same"); // 1.
}
if ( s1 == s3 ){
System.out.println("s1 and s3 are same" ); // 2.
}
if ( s1 == s4 ){
System.out.println("s1 and s4 are same" ); // 3.
}
if ( s1 == s5 ){
System.out.println("s1 and s5 are same" ); // 4.
}
将返回:
s1 and s2 are same
s1 and s3 are same
s1 and s5 are same
在所有情况下,除了 s4
变量,使用 new
操作符显式创建的值,并且没有使用 intern
方法根据它的结果,它是一个单一的不可变实例,正在返回 JVM 的字符串常量池.
In all the cases besides of s4
variable, a value for which was explicitly created using new
operator and where intern
method was not used on it's result, it is a single immutable instance that's being returned JVM's string constant pool.
有关详细信息,请参阅JavaTechniquesString Equality and Interning".
Refer to JavaTechniques "String Equality and Interning" for more information.
这篇关于我们什么时候应该在字符串文字上使用字符串的实习生方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!