V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
lixiaolin123
V2EX  ›  问与答

关于 String#intern

  •  
  •   lixiaolin123 · 23 天前 · 813 次点击

    public Class Example{ public static void main(String[] args) { String s = new String("1"); s.intern(); String s2 = "1"; System.out.println(s == s2);

    String s3 = new String("1") + new String("1");
    s3.intern();
    String s4 = "11";
    System.out.println(s3 == s4);
    

    } }

    这段代码的我机器上输出结果是 false false.但我看到原文 https://tech.meituan.com/2014/03/06/in-depth-understanding-string-intern.html 的结果是 false true.所以到底结果应该是什么?

    第 1 条附言  ·  23 天前

    重新排版修改:

    public class Example{   
      public static void main(String[] args) {
        String s = new String("1");
        s.intern();
        String s2 = "1";
        System.out.println(s == s2);
    
        String s3 = new String("1") + new String("1");
        s3.intern();
        String s4 = "11";
        System.out.println(s3 == s4);
     }
    }
    
    第 2 条附言  ·  22 天前

    代码1:

    public class Main {
      public static void main(String[] args) {
        String s = new String("1");
        s.intern();
        String s2 = "1";
        System.out.println(s == s2);
    
        String s3 = new String("1") + new String("1");
        s3.intern();
        String s4 = "11";
        System.out.println(s3 == s4);
      }
    }
    //false false
    

    代码2:

    public class Main {
      public static void main(String[] args) {
        String s = new String("1");
        s.intern();
        String s2 = "1";
        System.out.println(s == s2);
    
        String s3 = new String("呼喊哈虎") + new String("呼喊护花");
        s3.intern();
        String s4 = "呼喊哈虎呼喊护花";
        System.out.println(s3 == s4);
      }
    }
    //false true
    
    2 条回复    2024-08-29 13:36:17 +08:00
    newte88
        1
    newte88  
       23 天前
    s = s.intern();
    lixiaolin123
        2
    lixiaolin123  
    OP
       22 天前
    @newte88 感谢回答。

    我找到原因了。 一开始得到结果 false false 是因为我用的是公共在线 JVM https://www.bejson.com/runcode/java/

    第 2 条附言,比较一下代码 1 和代码 2 ,你应该也就知道原因了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1674 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 21ms · UTC 16:44 · PVG 00:44 · LAX 09:44 · JFK 12:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.