[英]How does String.intern() work and how does it affect the String pool?
我們知道, String().intern()
方法在字符串池中添加String值(如果它尚不存在)。 如果存在,則返回該值/對象的引用。
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()
這個實習方法會做什么?
在字符串池中添加帶有不同引用的“dog”或在字符串池中添加test
對象引用(我認為,情況並非如此)?
我試過這個
String test1 = "dog";
test == test1 // returns false
我只是想確保,當我調用test.intern()
它會在String池中創建具有相同值的新對象? 現在我有兩個值為“dog”的對象。 一個直接存在於堆中,另一個存在於String池中?
當我調用
test.intern()
這個實習方法會做什么?
它會將"dog"
字符串放在字符串池中(除非它已經存在)。 但它不一定會將test
所指的對象放在池中。 這就是你通常這樣做的原因
test = test.intern();
請注意,如果您的代碼中有"dog"
字面值,那么字符串池中已經存在"dog"
,因此test.intern()
將返回該對象。
也許你的實驗讓你困惑,實際上你想到的是以下實驗:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.