首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >字符串的intern()方法

字符串的intern()方法
EN

Stack Overflow用户
提问于 2014-05-18 15:36:38
回答 2查看 107关注 0票数 1

我遇到了来自intern()方法的以下行为,迷惑了,有什么想法吗?

案例1:

代码语言:javascript
复制
 String test3=new String("hello");  
 test3.intern();   
 String test4=new String("hello");   
 test4.intern();  
 if(test3==test4){   
    System.out.println("same obj refered for test3 and test4 ");  
 }  
 else{   
    System.out.println("new obj created for test4");   
 }  

输出:

代码语言:javascript
复制
new obj created for test4

案例2:

代码语言:javascript
复制
String test3=new String("hello").intern();   
//test3.intern();   
String test4=new String("hello").intern();   
//test4.intern();       
if(test3==test4){   
   System.out.println("same obj referred for test3 and test4 ");    
}
else{   
   System.out.println("new obj created for test4");    
}    

输出:

代码语言:javascript
复制
same obj referred for test3 and test4
EN

回答 2

Stack Overflow用户

发布于 2014-05-18 15:39:04

在CASE1中,您忽略了intern的返回值。这就是为什么变量仍然包含对原始string对象的引用。

要理解到底发生了什么,请考虑以下代码

代码语言:javascript
复制
    String test1 = "hello";
    String test2 = new String(test1);
    String test3 = test2.intern();
    System.out.println(test1 == test2);
    System.out.println(test1 == test3);

它打印出来

代码语言:javascript
复制
false
true

test1是在字符串池中分配的字符串文字"hello"test2是一个新的字符串对象,与test1不同,但具有相同的字符内容。它在堆上分配。test3intern的结果,因为在字符串池中已经存在字符串"hello",所以我们只需要返回对它的引用。因此,test3引用了与test1相同的对象。

票数 4
EN

Stack Overflow用户

发布于 2014-05-18 15:44:53

这是因为intern()方法返回一个内部字符串,它将指向内部池中的字符串实例,而不是堆中的字符串实例。If the String instance to be interned is already in the pool, reference to it is returned. If not then the String is added to the pool and reference to it is returned.,因此您应该比较由interned方法返回的字符串,而不是原始引用。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23719637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档