Java String Interning-什么,为什么和何时?
字符串实习不过是存储给定不同值的一个副本。这用于使字符串处理更加节省时间和空间。
String类的intern()方法返回字符串对象的规范表示。最初为空的字符串池由String类私有维护。
对于任何两个字符串s和t,当且仅当s.equals(t)为true时,s.intern()==t.intern()才为true。所有文字字符串和字符串值常量表达式均已插入。
示例
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str1 = "This is nhooo";
// returns canonical representation for the string object
String str2 = str1.intern();
// prints the string str2
System.out.println(str2);
// check if str1 and str2 are equal or not
System.out.println("Is str1 equal to str2 ? = " + (str1 == str2));
}
}输出结果
This is nhooo Is str1 equal to str2 ? = true