The return of String.intern() explained

前端 未结 3 1563
粉色の甜心
粉色の甜心 2020-12-20 11:54

Consider:

String s1 = new StringBuilder(\"Cattie\").append(\" & Doggie\").toString();
System.out.println(s1.intern() == s1); // true why?
System.out.prin         


        
3条回答
  •  -上瘾入骨i
    2020-12-20 12:06

    s2.intern() would return the instance referenced by s2 only if the String pool didn't contain a String whose value is "java" prior to that call. The JDK classes intern some Strings before your code is executed. "java" must be one of them. Therefore, s2.intern() returns the previously interned instance instead of s2.

    On the other hand, the JDK classes did not intern any String whose value is equal to "Cattie & Doggie", so s1.intern() returns s1.

    I am not aware of any list of pre-interned Strings. Such a list will most likely be considered an implementation detail, which may vary on different JDK implementations and JDK versions, and should not be relied on.

提交回复
热议问题