String.intern()如何工作以及它如何影响String池? [英] How does String.intern() work and how does it affect the String pool?
问题描述
如我们所知, String()。intern()
方法在字符串池中添加字符串值(如果它尚不存在)。如果存在,则返回该值/对象的引用。
As we know, String().intern()
method add String value in string pool if it's not already exist. If exists, it returns the reference of that value/object.
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()
这个实习方法会做什么?
I need to know, when i call test.intern()
what this intern method will do?
在字符串池中添加不同引用的dog或在字符串池中添加 test
对象引用(我认为,情况并非如此)?
add "dog" with different reference in string pool or add test
object reference in string pool(i think, it's not the case )?
我试过这个
String test1 = "dog";
test == test1 // returns false
我只是想制作当然,当我调用 test.intern()
时,它会在字符串池中创建具有相同值的新对象吗?现在我有两个值为dog的对象。一个直接存在于堆中,另一个存在于String池中?
I just want to make sure, when I call test.intern()
it creates new object with same value in String pool? now I have 2 objects with value "dog". one exist directly in heap and other is in String pool?
推荐答案
当我打电话给
test.intern()
这个实习方法会做什么?
when i call
test.intern()
what this intern method will do?
它会将dog
字符串放入字符串池中(除非它已经存在了)。但它不一定会将对象 c> test 引用到池中。这就是你通常做的原因
It will put the "dog"
string in the string pool (unless it's already there). But it will not necessarily put the object that test
refers to in the pool. This is why you typically do
test = test.intern();
请注意,如果你有dog
你的代码中的字面值,那么字符串池中已经存在dog
,所以 test.intern()
将返回该对象。
Note that if you have a "dog"
literal in your code, then there will already be a "dog"
in the string pool, so test.intern()
will return that object.
也许你的实验让你困惑,实际上你想到的是以下实验:
Perhaps your experiment confuses you, and it was in fact the following experiment you had in mind:
String s1 = "dog"; // "dog" object from string pool
String s2 = new String("dog"); // new "dog" object on heap
System.out.println(s1 == s2); // false
s2 = s2.intern(); // intern() returns the object from string pool
System.out.println(s1 == s2); // true
这篇关于String.intern()如何工作以及它如何影响String池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!