【发布时间】:2015-09-05 02:28:06
【问题描述】:
我们知道,String().intern() 方法在字符串池中添加字符串值,如果它不存在的话。如果存在,则返回该值/对象的引用。
String str = "Cat"; // creates new object in string pool with same character sequence.
String st1 = "Cat"; // has same reference of object in pool, just created in case of 'str'
str == str1 //that's returns true
String test = new String("dog");
test.intern();// what this line of code do behind the scene
我需要知道,当我调用test.intern() 时,这个实习生方法会做什么?
在字符串池中添加具有不同引用的“狗”或在字符串池中添加test对象引用(我认为不是这样)?
我试过了
String test1 = "dog";
test == test1 // returns false
我只是想确定,当我调用test.intern() 时,它会在字符串池中创建具有相同值的新对象吗?现在我有 2 个值为“dog”的对象。一个直接存在于堆中,另一个存在于字符串池中?
【问题讨论】:
-
str == str //that's returns true错字? -
对不起,应该是 str == str1。让我编辑我的问题。
-
你读过Javadoc吗?
-
你应该使用
.equals()方法来比较字符串,而不是==