我们何时应该在字符串文字上使用String的实习方法 [英] When should we use intern method of String on String literals

查看:107
本文介绍了我们何时应该在字符串文字上使用String的实习方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 String #internon( )实习生方法如果在String池中找到String,则应该从String池返回String,否则将在String中添加新的字符串对象池和此String的引用被返回。

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相同将不会被打印。但结果是:两行都打印出来。这意味着,默认情况下,字符串常量被实现。但如果是这样,那么为什么我们需要实习生方法呢?换句话说,我们什么时候应该使用这种方法?

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自动实习字符串文字。这意味着在许多情况下,==运算符似乎对字符串的工作方式与对int或其他原始值的工作方式相同。

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

请参阅 JavaTechniques 字符串平等和实习以获取更多信息。

Refer to JavaTechniques "String Equality and Interning" for more information.

这篇关于我们何时应该在字符串文字上使用String的实习方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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