String intern详解

JDK1.8环境下:

调用intern会检查该字符串是否存在池中,有且和该字符串不相同(equals方法判断)则返回该字符串常量的引用,否则创建该常量并返回引用

API:

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. Otherwise, this String object is added to the pool and a reference to this String object is returned.

new产生的对象不放入池中

        String s1 = new String("a") + new String("a"); //s1指向堆中对象
        s1.intern();//s1池中无“aa”,加入到常量池中
        String s2 = "aa";// 因为池中有“aa”所以直接将将引用给s2
        System.out.println(s1 == s2);//true 所以s1和s2的地址相等
        String s1 = new String("a") + new String("a"); //s1指向堆中对象
        String s2 = "aa";// 池中无“aa”,加入到常量池中
        s1.intern();//池中有"aa"返回引用,但是没有意义
        System.out.println(s1 == s2);//false 所以s1和s2的地址不相等

单个newString()和上面一样,同理

        String s1 = new String("a"); //s1指向堆中对象
        s1.intern();//s1池中无“a”,加入到常量池中
        String s2 = "a";// 因为池中有“a”所以直接将将引用给s2
        System.out.println(s1 == s2);//true 所以s1和s2的地址相等
        String s1 = new String("a"); //s1指向堆中对象
        String s2 = "a";// 池中无“a”,加入到常量池中
        s1.intern();//池中有"aa"返回引用,但是没有意义
        System.out.println(s1 == s2);//false 所以s1和s2的地址不相等

问题来了??

        String s=new StringBuilder("aa").append("bb").toString();
        String s2=new StringBuilder("aa").toString();
        System.out.println(s.intern()==s);//true
        System.out.println(s2.intern()==s2);//false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值