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

    .

  • 相关阅读:
    IDEA mybatis no data source 警告
    Flex 本地化(多语言) 语言文件夹设置
    Flex中 将字符串转化为Datetime类
    Disabling Clang Compiler warnings
    didEndEditingRowAtIndexPath with nil indexPath
    万达的商业模式有什么独到之处
    微信公众平台入门到精通合集
    BeautifulSoup解析非标准HTML的问题
    《人件》与软件研发项目管理
    足球3v3心得
  • 原文地址:https://www.cnblogs.com/milton/p/7694955.html
Copyright © 2011-2022 走看看