我不应该做`String s = new String(“一个新的字符串”);`在Java
发布时间:2020-12-15 02:53:52 所属栏目:Java 来源:网络整理
导读:好的,这个问题是这个问题的延伸 Java Strings: “String s = new String(“silly”);” 上面的问题提出了与此问题相同的问题,但我有一个新的疑点. 根据Effective Java和上面的问题的答案,我们不应该做String s = new String(“一个新的字符串”);,因为那会创
好的,这个问题是这个问题的延伸
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |