public native String intern(); java doc says,
一个字符串池,最初是空的,由类 >{@code String} 私下维护。当调用 intern 方法时,如果池已经 > 包含一个等于此 {@code String} 对象的字符串,该字符串由 > {@link #equals(Object)} 方法确定,则 > 返回池中的字符串。否则,这个 {@code String} 对象被添加到池中并且 > 一个对这个 {@code String} 对象的引用被返回。因此 > 对于任何两个字符串 {@code s} 和 {@code t},{@code s.intern() == >t.intern()} 是 {@code true} 当且仅当 {@code s.equals(t)} 是 {@code >true}。
让我们考虑一个例子:
String temp1 = new String("abcd"); 这意味着,将在heap memory 中创建一个新对象"abcd",其引用将链接到temp1。
String temp2 = new String("abcd").intern(); 这意味着"abcd" 文字将在String Pool 中检查。如果已经存在,它的引用将链接到新创建的temp2。否则将在String Pool 中创建一个新条目,其引用将链接到新创建的temp2。
String temp3 = "abcd"; 这意味着"abcd" 文字将在String Pool 中检查。如果已经存在,它的引用将链接到新创建的temp2。否则将在String Pool 中创建一个新条目,其引用将链接到新创建的temp3。由此得出结论,Java 自动实习字符串字面量。
让我们考虑另一个例子:
String s1 = "string-test";
String s2 = new String("string-test");
String s3 = new String("string-test").intern();
if ( s1 == s2 ){
System.out.println("s1 and s2 are same");
}
if ( s2 == s3 ){
System.out.println("s2 and s3 are same" );
}
if ( s1 == s3 ){
System.out.println("s1 and s3 are same" );
}
输出:s1 and s3 are same
现在何时使用= " " 或new String(" ") 创建字符串对象?
我遇到的一个用例,
// imagine a multi-megabyte string here
String s = "0123456789012345678901234567890123456789";
String s2 = s.substring(0, 1);
s = null;
您现在将拥有一个 String s2,虽然它看起来是一个单字符的字符串,但它包含对在 String s 中创建的巨大 char 数组的引用。这意味着数组不会被垃圾回收,即使我们已经明确地清空了 String s!
解决方法是像这样使用 String 构造函数:
String s2 = new String(s.substring(0, 1));