先說String,它是一個finally類,即不可被繼承,其方法默認也是finally不可被重寫。查看源碼可知intern是一個內部方法,下面是jdk11裏的原文:
/**
* 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™ 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.
* @jls 3.10.5 String Literals
*/
public native String intern();
這是一個native方法,由String類私有的維護這個String池,它保證池內每個數據都只有一份。若有新的String對象賦值會先在String池中查找該值是否存在,存在則直接將引用指向該值,不存在則創建新的值。注意,用new創建字符串會創建兩個數據,一個在堆裏創建,一個是在String池,創建後引用會指向堆中數據,調用intern方法後指向String池數據。
具體看下面的例子
String a = "asdf";
String b = "as";
String c = "df";
String d = b+c;
String e = "as"+"df";
String f = new String("asdf");
String g = new String("as")+new String("df");
String h = "as" + new String("df");
String i = new String("as") + "df";
String aa = "1111";
String bb = new String("11") + new String("11");
System.out.println("================"); // ================
System.out.println(a == d); // false 引用地址不同
System.out.println(a == e); // true 引用地址相同,String池只會維護一份數據,數據相同時直接修改引用不會新建相同的數據
System.out.println(d == e); // false
System.out.println(a == d.intern()); // true intern()指向String池中的值
System.out.println("================"); // ================
System.out.println(a == f); // false new在堆中創建,等號賦值在String池中
System.out.println(a == g); // false
System.out.println(a == h); // false
System.out.println(a == i); // false
System.out.println(a == f.intern()); // true 調用intern後引用就指向了String池中的數據
System.out.println(a == g.intern()); // true
System.out.println(a == h.intern()); // true
System.out.println(a == i.intern()); // true
System.out.println("================"); // ================
System.out.println(f == g); // false
System.out.println(f == d); // false
System.out.println(f.intern() == d); // false
System.out.println(f == d.intern()); // false
System.out.println(f.intern() == d.intern()); // true
System.out.println(aa == bb); // false
System.out.println(aa == bb.intern()); // true
System.out.println("================"); // ================