3 回答

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超6個(gè)贊
也許這有助于您理解:
String literal = "test";String one = new String(literal);String two = "test";System.out.println(literal == two); //trueSystem.out.println(one == two); //false
在您發(fā)布的示例中:
String one = new String("test");String two = "test";
由于實(shí)習(xí),傳遞給構(gòu)造函數(shù)的引用與引用String(String)
具有相同的值two
。但是,字符串本身(由這兩個(gè)引用引用)用于構(gòu)造分配給引用的新對象one
。
在這個(gè)例子中,正好有兩個(gè)String
用值“test”創(chuàng)建:一個(gè)在常量池中維護(hù)并"test"
在表達(dá)式中使用文字時(shí)引用,第二個(gè)由“new”運(yùn)算符創(chuàng)建并分配給參考one
。
編輯
也許你對這句話感到困惑:
當(dāng)編譯器遇到String文本時(shí),它會檢查池以查看是否已存在相同的String。
請注意,這可能更明確地說明如下:
當(dāng)編譯器遇到String文本時(shí),它會檢查池中是否已存在相同的String 。
字符串只有在明確地實(shí)現(xiàn)或通過類使用文字時(shí)才放入池中。例如,如果你有這種情況:
String te = "te";String st = "st";String test = new String(te) + new String(st);
然后當(dāng)一個(gè)String
將存在該值時(shí)test
,表示字符串將不存在于池中,因?yàn)槲淖?code>"test"從未發(fā)生過。

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超7個(gè)贊
//Creates a new object even if one exists in the pool String s1 = new String("Tendulkar"); // makes a new object string and then the reference is available to the pool String s2 = s1.intern(); //this object is not created but references the address present in the pool String s3 = "Tendulkar"; System.out.print(s1==s2); // results in false System.out.print(s2==s3); //very very true !!!

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊
你的問題 :
因此,當(dāng)我們使用“new”并基于上面的定義創(chuàng)建對象時(shí),我們還在非池內(nèi)存和池內(nèi)存中放置引用。當(dāng)我們這樣做時(shí),JVM是否也應(yīng)該返回相同的引用?:
Ans:使用new關(guān)鍵字創(chuàng)建新的字符串對象時(shí),生成的地址將是堆地址,而不是字符串常量池地址。兩個(gè)地址都不同。
問題:
String one = new String("test");
String two = "test";
System.out.println(one.equals(two)); // true
System.out.println(one == two); // false
以前的語句是否意味著它們將被放入池內(nèi)存中,但在使用new運(yùn)算符時(shí)會被跳過?
答:是的,您的假設(shè)是正確的。當(dāng)程序員使用new關(guān)鍵字時(shí),JVM將忽略關(guān)于字符串常量池,并在Heap中創(chuàng)建一個(gè)新副本。因此兩個(gè)地址都不相同。
添加回答
舉報(bào)