zoukankan      html  css  js  c++  java
  • Java中的String pool

    public String intern()
    返回字符串对象的规范化表示形式。

    一个初始时为空的字符串池,它由类 String 私有地维护。当调用 intern 方法时,如果池已经包含一个等于此 String 对象的字符串(该对象由 equals(Object) 方法确定),则返回池中的字符串。否则,将此 String 对象添加到池中,并且返回此 String 对象的引用。
    它遵循对于任何两个字符串 s 和 t,当且仅当 s.equals(t) 为 true 时,s.intern() == t.intern() 才为 true。
    所有字面值字符串和字符串赋值常量表达式都是内部的。

    返回:
    一个字符串,内容与此字符串相同,但它保证来自字符串池中。

    # 使用常量赋值时, 指向的是pool中的引用
    String s0 = "HelloWorld"; // id:24
    # 指向的是相同的引用
    String s00 = "HelloWorld"; // id:24 System.out.println(s00 == s0);//true
    # 使用变量赋值时, 是新的对象 String s1 = "Hello".concat("World"); // id:27
    System.out.println(s1 == s0);
    # 使用变量赋值时, 是新的对象, 但是内部的参数, 实际也是指向pool中的对象
    String s10
    = new String("HelloWorld"); // id:24 System.out.println(s10 == s0);
    # 使用intern会直接指回pool中的对象 String s2
    = s1.intern(); // id:24 System.out.println(s2 == s0);
    # 再次调用并不会修改这种关系 String s3
    = s2.intern(); // id:24 System.out.println(s3 == s2);//true System.out.println(s3 == s0);//true System.out.println(); String a = new String("ab"); String b = new String("ab"); String c = "ab"; String d = "a" + "b"; String e = "b";
    # 使用变量赋值时, 会产生新的对象引用 String f
    = "a" + e; System.out.println(b.intern() == a); System.out.println(b.intern() == c); // true System.out.println(b.intern() == d); // true System.out.println(b.intern() == f); System.out.println(b.intern() == a.intern()); // true

    .

  • 相关阅读:
    C# Socket 实现WebSocket服务器端
    Linux Vi 的使用
    Microsoft Sql Server 2016安装在CentOS7下
    通过反射获取所有继承了某一接口的类
    Windows下常用的100个CMD指令以及常见的操作
    CentOS系统安装遇到的一些问题
    SQL Server 2016最值得关注的10大新特性
    用注册表禁止windows添加新用户
    ASP.NET MVC学习之模型验证详解
    (转)RBAC权限管理
  • 原文地址:https://www.cnblogs.com/milton/p/7694955.html
Copyright © 2011-2022 走看看