首页 >Java >java教程 >什么时候应该对 Java 字符串使用'intern()”方法?

什么时候应该对 Java 字符串使用'intern()”方法?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-12-06 10:37:11711浏览

When Should You Use the `intern()` Method for Java Strings?

何时对字符串文字使用 intern 方法

使用文字语法(“String”)创建的字符串会自动驻留在字符串池中通过 JVM。因此,== 运算符对于字符串文字的行为是一致的。

但是,对于使用 new String() 创建的字符串来说,驻留并不是自动的。这是 intern() 方法发挥作用的地方。

在使用 new String() 创建的 String 上使用 intern() 方法会将该 String 添加到池中,并返回现有的对象实例(如果已存在相同的 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");
}

if (s1 == s3) {
    System.out.println("s1 and s3 are same");
}

if (s1 == s4) {
    System.out.println("s1 and s4 are same");
}

if (s1 == s5) {
    System.out.println("s1 and s5 are same");
}

输出将be:

s1 and s2 are same
s1 and s3 are same
s1 and s5 are same

除了 s4 之外的所有情况,其中 String 是使用 new 显式创建而不是 interned,JVM 的字符串常量池返回相同的不可变实例。

请参阅 JavaTechniques “字符串相等和实习”了解更多详细信息。

以上是什么时候应该对 Java 字符串使用'intern()”方法?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn