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

别来无恙 提交于 2019-12-07 02:56:49

问题


Ok, this question is an extension of this question

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

The above question asked the same question as this one, but I have a new doubting point.

According to Effective Java and the answers of above question, we should not do String s = new String("a new string");, because that will create unnecessary object.

I am not sure about this conclusion, because I think Java is doing automatic string interning, which means for a string, anyway there is only one copy of it in the memory.

So let's see String s = new String("a new string");.

"a new string" is already a string which has been created in the memory.

When I do String s = new String("a new string");, then the s is also "a new string". So according to automatic string interning, s should be pointed to the same memory address of "a new string", right?

Then how can we say we create unnecessary objects?


回答1:



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



回答2:


You may want to read more about String literal pool in JVMs. Quick googling pointed me to this article: http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3 which seems quite valid.

Also you may be interested in Integer literal pooling as well as other literals pooling in Java.




回答3:


using "=" instead of "=new String" is better since it might result in a single instance instead of multiple instances.



来源:https://stackoverflow.com/questions/10666537/shouldnt-i-do-string-s-new-stringa-new-string-in-java-even-with-autom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!