比方说,我们有以下的代码Java的字符串文字池
String x = new String("xyz");
String y = "abc";
x = x + y;
我的一个朋友说,4个对象在总创建的,在这里我说只有3个被创建。有人可以解释背景中发生了什么吗?我已阅读过有关字符串文字池,但我可以找到答案。
我对创建3对象的解释如下:一个在编译时的字符串文字池(“abc”)和两个在堆上的运行时(“abc”和x + y)
比方说,我们有以下的代码Java的字符串文字池
String x = new String("xyz");
String y = "abc";
x = x + y;
我的一个朋友说,4个对象在总创建的,在这里我说只有3个被创建。有人可以解释背景中发生了什么吗?我已阅读过有关字符串文字池,但我可以找到答案。
我对创建3对象的解释如下:一个在编译时的字符串文字池(“abc”)和两个在堆上的运行时(“abc”和x + y)
4个对象被创建为遵循
// 1. "xyz" in the literal pool
// 2. a new String object which is a different object than "xyz" in the pool
String x = new String("xyz");
// 3. "abc" in the literal pool
String y = "abc";
// 4. new String object
x = x + y;
好吧,我想我已经开始明白了。这意味着如果我有'String y =“abc”; String x = new String(y); x = x + y'那么我只有3个物体? –
@CristianBalint你的假设是对的。 – SubOptimal
实际上..当两个字符串的值相同时,字符串池工作。例如,如果我们有String s1 =“abc”和s2 =“abc”,那么s1和s2都将指向相同的内存引用(或对象)。
在上述情况下,3个对象将在堆
创建对于x varible上堆
为变量y上堆
为X + Y的表达
将创建4个对象。
字符串是unmodifiable
所以每次将它们连接起来的新对象将在new String("xyz");
首先要创建"xyz"
的情况下创建
时间“XYZ”对象,然后把它传递到一个新的对象(字符串),因此,有在这里两个对象
new String("xyz") <--there are two objects
"abc" <-- kinda obvious
x + y <-- String are unmodifiable thus this is a new object
是代码将ç reate 4 objects
String x = new String("xyz"); // object#1 : xyz and Object #2: new String
String y = "abc"; // Object#3 : abc
x = x + y; // object#4 : xyzabc
你在说哪个JVM?它可能是特定于实现的。 –
无论JVM如何创建4个对象?第四个对象是什么? –
yep theres three,“xyz”,“abc”和“xyzabc”。 – ConMan