2.8关于String.intern()
**intern方法使用:**一个初始为空的字符串池,它由类String独自维护。当调用intern方法时,如果池已经包含一个等于此String对象的字符串(用equals(object)方法确定),则返回池中的字符串。否则,将此String对象添加到池中,并返回此String对象的引用。
它遵循以下规则:对于任意两个字符串s和t,当前仅当s.equals(t)为true是,s.intern()==t.intern()才为true。
String.intern();
再补充介绍一点:存在于.class文件中的常量池,在运行期间被JVM装载,并且可以扩充。String的intern()方法就是扩充常量池的一个方法;当一个String实例str调用intern方法时,java查找常量池中是否有相同unicode的字符串,如果有,则返回其引用,如果没有,则在常量池中增加一个unicode等于str的字符串并返回它的引用。
public void ex(){
String s0 = "wannabe";
String s1 = new String("wannabe");
String s2 = new String("wannabe");
System.out.println(s0 == s1); //false
s1.intern(); //虽然执行了s1.intern(),但它的返回值没有赋给s1
s2 = s2.intern(); //把常量池中的“wannabe”的引用赋给s2
System.out.println(s0 == s1); //false
System.out.println(s0 == s1.intern()); //true 说明s1.intern()返回的是常量中“wannabe”的引用
System.out.println(s0 == s2);//true
}
运行结果:
false false true true