我不应该做`String s = new String(“一个新的字符串”);`在Java中,即使是自动字符串实习? [英] Shouldn't I do `String s = new String("a new string");` in Java, even with automatic string interning?

查看:130
本文介绍了我不应该做`String s = new String(“一个新的字符串”);`在Java中,即使是自动字符串实习?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Ok, this question is an extension of this question

Java字符串:" String s = new String(" silly");"

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

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

根据 Effective Java 和答案在上面的问题中,我们应该 String s = new String(一个新字符串); ,因为这将创建不必要的对象。

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.

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

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.

所以让我们看看 String s = new String(一个新字符串);

新字符串已经是在内存中创建的字符串。

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

当我做 String s = new String(一个新字符串); ,然后 s 也是新字符串。因此,根据自动字符串实习 s 应该指向的相同内存地址一个新的字符串,对吗?

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?

推荐答案


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

这篇关于我不应该做`String s = new String(“一个新的字符串”);`在Java中,即使是自动字符串实习?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆