Java中intern()方法

看下面这段程序:

public static void main(String[] args) throws Exception {  

    String a =  "b" ;   

    String b =  "b" ;        

    System.out.print( a == b);         

    String c = "d" ;  

    String d = new String( "d" ).intern() ;   

    System.out.println( c == d);  

}   

这段程序输出的程序是true和true。

原因在于intern()方法返回的是字符串对象的规范化表示形式。当调用intern()方法时,如果池中已经包含了一个等于此String对象的字符串,则返回池中的字符串。否则,将此String对象添加到池中,并且返回此String对象的引用。这时候c和d就是相等的。

再看下面的这一段程序:

String s1 = "ab123" ;  

String s2 = new String( "ab123" ) ;  

System.out.println( s1 == s2 );   

String s3 = s2.intern() ;   

System.out.println( s1 == s3 ) ;  

输出的分别是false和true。

猜你喜欢

转载自blog.csdn.net/g1607058603/article/details/81842525
今日推荐