美文网首页
我对String.intern()的一些理解

我对String.intern()的一些理解

作者: gcno93 | 来源:发表于2021-09-20 03:15 被阅读0次

不多说直接看下面代码

   String s1 = new String("aaa");
   String s2 = "aaa";
   //s1.intern()把s1的"aaa"放进常量池,发现常量池已经存在"aaa",
   // 返回"aaa"常量池的地址
   System.out.println(s1.intern() == s2);  // true

    String s3 = new String("1") + new String("1");
    //s3.intern() 把s3的"11"放进常量池,发现常量池没有"11",
    // 则把s3的"11"地址放进常量池
    s3.intern();
    String s4 = "11";//常量池"11"地址就是s3地址
    System.out.println(s4 == s3);  //true


    String s5 = new String("1") + new String("1");
    String s6 = "11";
    //s5.intern() 把s5的"11"放进常量池,发现常量池已经存在"11",
    // 返回"11"常量池地址,但s5没有接收
    s5.intern();
    System.out.println(s5 == s6);  //false
    
    总结:
    intern 会先检查常量池中是否存在该字符串,
    存在,则返回常量池中的地址,
    不存在,则复制该字符串的引用地址到常量池

相关文章

网友评论

      本文标题:我对String.intern()的一些理解

      本文链接:https://www.haomeiwen.com/subject/ahlmgltx.html