我遇到了来自intern()方法的以下行为,迷惑了,有什么想法吗?
案例1:
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");
} 输出:
new obj created for test4案例2:
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");
} 输出:
same obj referred for test3 and test4发布于 2014-05-18 15:39:04
在CASE1中,您忽略了intern的返回值。这就是为什么变量仍然包含对原始string对象的引用。
要理解到底发生了什么,请考虑以下代码
String test1 = "hello";
String test2 = new String(test1);
String test3 = test2.intern();
System.out.println(test1 == test2);
System.out.println(test1 == test3);它打印出来
false
truetest1是在字符串池中分配的字符串文字"hello"。test2是一个新的字符串对象,与test1不同,但具有相同的字符内容。它在堆上分配。test3是intern的结果,因为在字符串池中已经存在字符串"hello",所以我们只需要返回对它的引用。因此,test3引用了与test1相同的对象。
发布于 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方法返回的字符串,而不是原始引用。
https://stackoverflow.com/questions/23719637
复制相似问题