深入理解String.intern()方法

时间:2024-04-15 09:37:15

  首先进入intern()的源码中,

    深入理解String.intern()方法

   首先说一点:1.7后的JVM为String在方法区中开辟了一个字符串常量池,如果一个String()不是new()出来的,都将在常量池中拿字符。

  注释翻译过来就是, 

      返回一个规范的字符串表现形式。

      字符串池初始是空的,由String维护。

      当调用intern(),如果在字符串池中含有(该字符串equals后的结果值),则返回字符串池中的结果值。(有点绕,意思就是有相同字符集的,就返回该字符集);

      如果没有,则将该字符集加入常量池中,再调用intern()。

          所以,任何的String类型比较其intern()时,都是比较equals值。

    配合下面示例,看的更清楚:

public class StringIntern {

    public static void main(String[] args) {
String s1 = "HelloWorld";
String s2 = new String("HelloWorld");
String s3 = "Hello";
String s4 = "World";
String s5 = "Hello" + "World";
String s6 = s3 + s4; System.out.println(s1 == s2); //false
System.out.println(s1 == s5); //true
System.out.println(s1 == s6); //false 此处s6=new String(s3 + s4)
System.out.println(s1 == s6.intern());//true
System.out.println(s2 == s2.intern());//false
} }