好的,这个问题是这个问题的延伸
Java Strings: “String s = new String(“silly”);”
上面的问题提出了与此问题相同的问题,但我有一个新的疑点.
根据Effective Java和上面的问题的答案,我们不应该做String s = new String(“一个新的字符串”);,因为那会创建不必要的对象.
我不确定这个结论,因为我认为Java正在执行automatic string interning,这意味着对于一个字符串,无论如何它只在内存中有一个副本.
所以让我们看看String s = new String(“一个新的字符串”);.
“新字符串”已经是在内存中创建的字符串.
当我执行String s = new String(“一个新字符串”);,那么s也是“一个新字符串”.所以根据自动字符串实习,s应该指向“新字符串”的相同内存地址,对吧?
那我们怎么说我们创造了不必要的对象呢?
解决方法
- 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