1. intern()
《深入理解Java虚拟机》中的描述:
- String.intern()是一个Native方法,它的作用是:如果字符串常量池中已经包含一个等于此String对象的字符串,则返回代表池中这个字符串的String对象;否则,将此Sreing对象包含的字符串添加到常量池中,并且返回此String对象的引用。
- Jdk1.7的intern()实现不会再复制实例,只是在常量池中记录首次出现的实例引用。
String源码注释:
- When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
【例1】
代码1:
String s1=new String("11")+new String("11");
s1.intern();
String s2="1111";
System.out.println(s1==s2); //true
代码2:
String s1=new String("11")+new String("11");
String s2="1111";
System.out.println(s1==s2); //false
解释:String s1=new String(“11”)+new String(“11”);在堆中存”1111“,在常量池中存”11“,当执行intern()的时候,因为常量池中没有”1111“,所以就把堆中的”1111“的实例引用放到常量池中。当执行String s2="1111"的时候,首先去常量池看看有没有“1111”,这时发现有,就得到了s1的引用,所以s1==s2是true;而不执行s1.intern()时,由于s1是堆中存的引用,s2是常量池的,所以s1!=s2。