JAVA intern()方法学习

时间:2023-02-25 16:53:22

intern()方法和前面说的equals()方法关系密切,从public native String intern()看出,它是Java的本地方法,我们先来看看Java文档里的描述:

Returns a canonical representation for the string object.  
A pool of strings, initially empty, is maintained privately by the  
class String.When the intern method is invoked, if the pool already contains a  
string equal to this String object as determined by  
theequals(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.  
It follows that for any two strings s and t,  
s.intern()==t.intern() is true if and only if s.equals(t) is true.  
All literal strings and string-valued constant expressions are interned.   
@return  a string that has the same contents as this string, but is  
guaranteed to be from a pool of unique strings.


意思就是说,返回字符串一个规范的表示。进一步解释:有两个字符串s和t,s.equals(t),则s.intern()==t.intern().
举个例子:
public class StringTest {  
    public static void main(String[] args) {  
        String s = new String("abc");  
        String s1 = "abc";  
        String s2 = "abc";  
        String s3 = s.intern();  
        System.out.println(s == s1);//false  
        System.out.println(s == s2);//false  
        System.out.println(s == s3);//false  
        System.out.println(s1 == s3);//true        
    }  

}

输出结果如注释所示,前两个结果前面已经说的很清楚了,现在拿最后一个说明,首先看看s3 = s.intern()这句,当调用s.intern()这句的时候,先去字符串常量池中找,是否有abc这个串,如果没有,则新增,同时返回引用,如果有,则返回已经存在的引用,此处s1和s2都指向常量池中的abc对象,所以此处是存在的,调用s.intern()后,s3和s1、s2指向同一个对象,所以s1==s3返回的是true。
intern()做到了一个很不寻常的行为:在运行期动态的在方法区创建对象,一般只有像new关键字可以在运行期在堆上面创建对象,所以此处比较特殊。属于及时编译的概念。
一般常见的字符串处理函数就这些,其它的还有很多,就不一一列举。