[String] intern()方法

 intern()方法设计的初衷,就是重用String对象,以节省内存消耗。

  JDK1.6以及以前版本中,常量池是放在 Perm 区(属于方法区)中的,熟悉JVM的话应该知道这是和堆区完全分开的。

使用引号声明的字符串都是会直接在字符串常量池中生成的,而 new 出来的 String 对象是放在堆空间中的。所以两者的内存地址肯定是不相同的,即使调用了intern()方法也是不影响的。

 JDK1.7后,常量池被放入到堆空间中,这导致intern()函数的功能不同。

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

一个初始为空的字符串池,它由类 String 私有地维护。

当调用 intern 方法时,如果池已经包含一个等于此 String 对象的字符串(用 equals(Object) 方法确定),则返回池中的字符串。否则,将此 String 对象添加到池中,并返回此 String 对象的引用。

它遵循以下规则:对于任意两个字符串 st,当且仅当 s.equals(t)true 时,s.intern() == t.intern() 才为 true

所有字面值字符串和字符串赋值常量表达式都使用 intern 方法进行操作。字符串字面值在 Java Language Specification 的 §3.10.5 定义。

返回:一个字符串,内容与此字符串相同,但一定取自具有唯一字符串的池。
public class StringDemo {
    public static void main(String[] args) {
        String a = "abcd" + "";
        String b = "abcd";
        String c = new String("abcd");
        String d = new String("abcd").intern();

        System.out.println("a == b:" + (a == b));
        System.out.println("a == c:" + (a == c));
        System.out.println("b == d:" + (b == d));
        System.out.println("c == d:" + (c == d));
        System.out.println("a == d:" + (a == d));

        System.out.println(a.equals(b));
        System.out.println(a.equals(c));
        System.out.println(a.equals(d));
        System.out.println(c.equals(d));
    }
}
//输出结果

a == b:true
a == c:false
b == d:true
c == d:false
a == d:true
true
true
true
true

原文地址:https://www.cnblogs.com/lanseyitai1224/p/6955438.html