理解String.intern()

  • java.lang.String
/**
     * Returns a canonical representation for the string object.
     * <p>
     * A pool of strings, initially empty, is maintained privately by the
     * class {@code String}.
     * <p>
     * When the intern method is invoked, if the pool already contains a
     * string equal to this {@code String} object as determined by
     * the {@link #equals(Object)} method, then the string from the pool is
     * returned. Otherwise, this {@code String} object is added to the
     * pool and a reference to this {@code String} object is returned.
     * <p>
     * It follows that for any two strings {@code s} and {@code t},
     * {@code s.intern() == t.intern()} is {@code true}
     * if and only if {@code s.equals(t)} is {@code true}.
     * <p>
     * All literal strings and string-valued constant expressions are
     * interned. String literals are defined in section 3.10.5 of the
     * <cite>The Java&trade; Language Specification</cite>.
     *
     * @return  a string that has the same contents as this string, but is
     *          guaranteed to be from a pool of unique strings.
     */
    public native String intern();

  • intern方法用来返回常量池中的某字符串,如果常量池中已经存在该字符串,则直接返回常量池中该对象的引用。否则,则常量池中加入该对象,然后返回引用。

String设计成不可变的原因

  • 字符串常量池的需要。字符串常量池的诞生可以提高效率,减少内存分配。String的不可变,常量池可以很容易的被管理和优化。
  • 安全性考虑。字符串使用的场景很多,设计成不可变的可以有效的防止字符串被有意或无意的被篡改。
  • 作为HashMap、HashTable等hash类型key的必要。因为String被设计成不可变的,JVM底层很容易在缓存String对象的时候缓存其hsahCode,这样在执行效率上会大大提升。

创建字符串

  • 直接使用双引号创建字符串
    • 判断这个常量是否存在于常量池
      • 如果存在,判断这个常量是存在的引用还是常量
        • 如果是引用,则返回引用地址指向的堆空间对象
        • 如果是常量,则直接返回常量池常量
      • 如果不存在
        • 在常量池中先创建该常量,并返回此常量
        String s1 = "hello";  // 在常量池中创建常量
        String s2 = "hello";  // 直接返回已经存在的常量
        String s1 = "hello";
        String s2 = "hello";
        System.out.println(s1 == s2);        // true
        System.out.println(s1.equals(s2));    // true
        String s1 = new String("hello");  // 在堆上创建字符串对象
        s1.intern();    // 在常量池中创建对象的引用
        String s2 = "hello";  // 常量池中存在该常量,直接返回该引用指向的堆空间对象
        String s1 = new String("hello").intern();
        String s2 = "hello";
        System.out.println(s1 == s2);      // true
        System.out.println(s1.equals(s2));      // true
  • new String();
    • 首先在堆上创建对象
    • 然后判断常量池上是否存在字符串的字面量
      • 如果不存在,在常量池中创建常量
      • 如果存在,不做任何操作
        String s1 = new String("hello");
        String s2 = new String("hello");
        System.out.println(s1 == s2);      // false
        System.out.println(s1.equals(s2));    // true
        String s1 = new String("hello").intern();
        String s2 = new String("hello").intern();
        System.out.println(s1 == s2);    // true
        System.out.println(s1.equals(s2));    // true
        String s1 = new String("hello").intern();
        String s2 = "hello";
        System.out.println(s1 == s2);    // true
        System.out.println(s1.equals(s2));  // true
  • String.valueOf();
    /**
     * Returns the string representation of the {@code Object} argument.
     *
     * @param   obj   an {@code Object}.
     * @return  if the argument is {@code null}, then a string equal to
     *          {@code "null"}; otherwise, the value of
     *          {@code obj.toString()} is returned.
     * @see     java.lang.Object#toString()
     */
    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }
        String s1 = String.valueOf("hello");
        String s2 = "hello";
        System.out.println(s1 == s2);    // true
        System.out.println(s1.equals(s2));    // true
        String s1 = String.valueOf("hello");
        String s2 = String.valueOf("hello");
        System.out.println(s1 == s2);    // true
        System.out.println(s1.equals(s2));    // true
        String s1 = String.valueOf("hello");
        String s2 = new String("hello").intern();
        System.out.println(s1 == s2);    // true
        System.out.println(s1.equals(s2));    // truee
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 RTFSC (Read the fucking source code )才是生活中最重要的。我们天天就是要...
    二毛_coder阅读 3,247评论 1 1
  • 从网上复制的,看别人的比较全面,自己搬过来,方便以后查找。原链接:https://www.cnblogs.com/...
    lxtyp阅读 5,142评论 0 9
  • 注:都是在百度搜索整理的答案,如有侵权和错误,希告知更改。 一、哪些情况下的对象会被垃圾回收机制处理掉  当对象对...
    Jenchar阅读 8,428评论 3 2
  •   需要说明的一点是,这篇文章是以《深入理解Java虚拟机》第二版这本书为基础的,这里假设大家已经了解了JVM的运...
    Geeks_Liu阅读 14,759评论 5 44
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,794评论 1 32