Java字符串池对象的创建

4
我怀疑我的stringpool概念是否清晰。请查看以下一组代码,并检查在以下语句集之后创建的对象数量是否正确:-
1)
String s1 = "abc";
String s2 = "def";
s2 + "xyz";

2)
 String s1 = "abc";
 String s2 = "def";
 s2 = s2 + "xyz";

3)
String s1 = "abc";
String s2 = "def";
String s3 = s2 + "xyz";

4)

String s1 = "abc";
String s2 = "def";
s2 + "xyz";
String s3 = "defxyz";

据我所知,从概念上讲,在上述4种情况中,每组代码执行后都会创建4个对象。

告诉我们为什么在第3个例子中有4个对象。 - djna
在前三个中,每个只有3个字符串对象... - Jon Skeet
@djna: 是的。编译器可以自由地只使用三个对象,因为 s2 + "xyz" 可以在编译时评估。 - Thilo
@John Skeet:为什么最后一个也不行呢? - Thilo
@Thilo,最后一个示例中有4个不同的文字。我想我们没有考虑死代码消除。 :) - Ray Toal
显示剩余2条评论
2个回答

8

您不能像s2 + "xyz"这样单独使用表达式。编译器只会评估常量,并且只有字符串常量会自动添加到字符串文字池中。

例如:

final String s1 = "abc"; // string literal
String s2 = "abc"; // same string literal

String s3 = s1 + "xyz"; // constants evaluated by the compiler 
                        // and turned into "abcxyz"

String s4 = s2 + "xyz"; // s2 is not a constant and this will
                        // be evaluated at runtime. not in the literal pool.
assert s1 == s2;
assert s3 != s4; // different strings.

1

你为什么在意呢?这取决于编译器的优化程度,因此没有实际上的正确答案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接