我不应该做`String s = new String(“一个新字符串”);`在Java中,即使是自动字符串实习?

时间:2012-05-19 15:29:31

标签: java string object string-interning

好的,这个问题是这个问题的延伸

Java Strings: "String s = new String("silly");"

上述问题提出了与此问题相同的问题,但我有一个新的疑点。

根据Effective Java和上述问题的答案,我们应该执行String s = new String("a new string");,因为这会产生不必要的对象。

我不确定这个结论,因为我认为Java正在做automatic string interning,这意味着对于一个字符串,无论如何它只在内存中有一个副本。

让我们看看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"的相同内存地址,对吧?

那我们怎么说我们创造了不必要的对象?

3 个答案:

答案 0 :(得分:16)


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

答案 1 :(得分:2)

您可能希望在JVM中阅读有关字符串文字池的更多信息。快速谷歌搜索指向我这篇文章: http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3 这似乎很有效。

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

答案 2 :(得分:0)

使用“=”而不是“= new String”更好,因为它可能导致单个实例而不是多个实例。