字符串是Java编程中最常用到的数据类型。关于字符串的知识总是常看常新。今天来说一说关于Java中intern()方法的解析作用。
它是一个本地方法(由Java语言外的语言编写),因此在jdk1.8源码中没有其实现,不过有一段描述,讲述了它的作用。
/**
* 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.
*/
public native String intern();
JDK文档中说的比较清楚:
当调用intern方法时,如果池已经包含
所确定的这个{@code string}对象
{@link #equals(Object)}方法,然后是来自poo的字符串
返回。否则,此{@code String}对象将添加到
池和对这个{@code String}对象的引用被返回
intern代码测试:
public class InternTest {
public static void main(String[] args) {
String a = new String("abc");
// 第一次,创建了两个对象,一个是堆中的string对象,一个是常量池中的"abc"
String b = new String("abc");
// 第二次,创建一个对象,堆中的另外一个string对象
System.out.println(a.intern() == b.intern());// true
System.out.println(a.intern() == b);// false
System.out.println(a.intern() == a);// false
/*
* intern方法会到常量池中查找是否存在该对象,如果存在,返回该对象。不存在的话就创建该对象并返回该对象(jdk1.6),(jdk1.7)
* 会在常量池中存一个指向堆中的那个对象的引用。 不存在往往是String s3 = new String("1") + new
* String("1");这种形式,会在堆中有一个s3指向的11的对象和常量池中的1对象
* 在这里就是体现的堆中的内存地址不一样,但对应的同一个常量池中的string 第一个比较时常量池中的该对象和自身比较
* 下面两个比较则是常量池中的对象和堆中的两个对象进行比较
*/
String poolstr = "abc";
// 直接从字符串常量池中获取
System.out.println(a.intern() == poolstr);// true
System.out.println(b.intern() == poolstr);// true
/*
* 这里新声明并赋值了一个poolstr,值为常量池中的字符串"abc",将它和a.intern()和b.inten()比较就是和自身比较
*/
String str = new String("a") + new String("b");
System.out.println(str.intern() == str);// true
/*
* str创建了3个对象,在堆中有一个"ab",在常量池中有一个"a"和"b" 比较str.intern()和str会得到true
* 在jdk1.7之后,会在常量池中存一个指向堆中的那个对象的引用。
* 调用str.intern()会在常量池中存储一个指向堆中"ab"的引用,也就是说它和堆中的对象实际是等价的,因此==时返回true
*/
String strtwo = "ab";
System.out.println(strtwo == str);// true
/*
* 常量池中已存在ab,所以会直接将strtwo指向常量池中的"ab",即堆中str对象的引用,因此相等
*/
}
}
总结String的intern()的使用:
●jdk1.6中,将这个字符串对象尝试放入串池。
➢如果串池中有,则并不会放入。返回已有的串池中的对象的地址
➢如果没有,会把此对象复制一份,放入串池,并返回串池中的对
象地址.
●
Jdk1.7起,将这个字符串对象尝试放入串池。
➢如果串池中有,则并不会放入。返回已有的串池中的对象的地址
➢如果没有,则会把对象的引用地址复制一份,放入串池,并返回
串池中的引用地址