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

Jac*_*ale 6 java string object 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 interning,s应该指向相同的内存地址"a new string",对吧?

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

Con*_*Del 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
Run Code Online (Sandbox Code Playgroud)