简体   繁体   English

String.intern() 显示奇怪的结果,它是如何工作的

[英]String.intern() shows strange result, how does it work

I know that String.intern() adds string to pool if it does not contain the object, but how to explain the results.我知道如果 String.intern() 不包含 object,则将字符串添加到池中,但是如何解释结果。

The code below:下面的代码:

public static void main(String[] args) {

        char[] abc = new char[]{'a','b','c'};
        String str = new String(abc);
        System.out.println(str == "abc");
        str.intern();
        System.out.println(str == "abc");
    }

output is: output 是:

false错误的

false错误的

However when code as below:但是,当代码如下:

public static void main(String[] args) {

        char[] abc = new char[]{'a','b','c'};
        String str = new String(abc);
        str.intern();
        System.out.println(str == "abc");
    }

The output is: output 是:

true真的

What's the difference.有什么不同。

The difference is that when you use the String literal "abc" before the explicit call to intern , it is implicitly interned.不同之处在于,当您在显式调用intern之前使用String文字“abc”时,它是隐式实习的。

str.intern() doesn't store the instance referenced by str in the String pool if an equal String is already in the pool.如果池中已经存在相等的String ,则str.intern()不会将str引用的实例存储在字符串池中。

First snippet:第一个片段:

System.out.println(str == "abc"); // "abc" is interned
str.intern(); // str is not stored in the pool
System.out.println(str == "abc"); // returns false

Second snippet:第二个片段:

str.intern(); // str is stored in the pool
System.out.println(str == "abc"); // returns true

From the Javadoc of intern:来自实习生的 Javadoc:

String java.lang.String.intern()字符串 java.lang.String.intern()

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 .当调用 intern 方法时,如果池中已经包含一个等于该 String object 的字符串,由 equals(Object) 方法确定,则返回池中的字符串 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 .否则,此字符串 object 将添加到池中,并返回对此字符串 object 的引用...所有文字字符串和字符串值常量表达式都是 interned

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM