I shouldn’t do ` string s = new string (“a new string”)` In Java, even automatic string practice?

Well, this problem is an extension of this problem

Java Strings: “String s = new String(“silly”);”

The above question raises the same question as this one, but I have a new doubt

According to effective Java and the answers to the above questions, we should not do string s = new string ("a new string");, Because that creates unnecessary objects

I'm not sure about this conclusion, because I think Java is executing automatic string interning, which means that for a string, it only has one copy in memory anyway

So let's look at string s = new string ("a new string")

"New string" is already a string created in memory

When I execute string s = new string ("a new string");, Then s is also "a new string" So according to the automatic string practice, s should point to the same memory address of "new string", right?

So how do we say we create unnecessary objects?

Solution

String a = "foo"; // this string will be interned
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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>