簡體   English   中英

我不應該做`String s = new String(“一個新字符串”);`在Java中,即使是自動字符串實習?

[英]Shouldn't I do `String s = new String(“a new string”);` in Java, even with automatic string interning?

好的,這個問題是這個問題的延伸

Java字符串:“String s = new String(”傻“);”

上面的問題提出了與此問題相同的問題,但我有一個新的疑點。

根據Effective Java和上面的問題的答案,我們應該做String s = new String("a new string"); ,因為那會產生不必要的對象。

我不確定這個結論,因為我認為Java正在進行自動字符串實習 ,這意味着對於一個字符串,無論如何在內存中只有一個副本。

那么讓我們看看String s = new String("a new string");

"a new string"已經是在內存中創建的字符串。

當我做String s = new String("a new string"); ,那么s也是"a new string" 所以根據automatic string internings應該指向"a new string"的相同內存地址,對吧?

那我們怎么說我們創造了不必要的對象呢?


String a = "foo"; // this string will be interned
String b = "foo"; // interned to the same string as a
boolean c = a == b; //this will be true
String d = new String(a); // this creates a new non-interned String
boolean e = a == d; // this will be false
String f = "f";
String g = "oo";
String h = f + g; //this creates a new non-interned string
boolean i = h == a // this will be false
File fi = ...;
BufferedReader br = ...;
String j = br.readLine();
boolean k = a == j; // this will always be false. Data that you've read it is not automatically interned

您可能希望了解有關JVM中的字符串文字池的更多信息。 快速的谷歌搜索向我指出了這篇文章: http//www.xyzws.com/Javafaq/what-is-string-literal-pool/3這似乎非常有效。

您也可能對Integer文字池以及Java中的其他文字池感興趣。

使用“=”而不是“= new String”更好,因為它可能導致單個實例而不是多個實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM