-2

我是 Java 新手,有一个与创建字符串有关的问题。

情况1:

String a = "hello";
String b = "world";
a = a + b;
System.out.println(a);

案例二:

String a;
String a = "hello";
a = new String("world");
System.out.println(a);

我想知道在每种情况下创建了多少个对象。因为 String 是不可变的,所以一旦为它分配了值,对象就不能被重用(这是我目前所理解的,如果我错了,请纠正我)。

如果有人能用 StringBuffer 解释同样的话,我会更高兴。谢谢。

4

3 回答 3

1
Case 1:

String a = "hello";  --  Creates  new String Object 'hello' and a reference to that obj
String b = "world";  --  Creates  new String Object 'world' and b reference to that obj
a        = a + b;     --  Creates  new String Object 'helloworld' and a reference to   that obj.Object "hello" is eligible for garbage collection at this point

So in total 3 String objects got created.

Case 2:

String a;  -- No string object is created. A String reference is created.
String a = "hello";  -- A String object "hello" is created and a reference to that
a        = new String("world");  -- A String object "world" is created and a reference to that. Object "hello" is eligible for garbage collection at this point


So in total 2 String objects got created
于 2013-04-04T04:04:39.303 回答
0

正如您正确提到的字符串是immutable,下面创建3 string literal objects

String a = "hello"; --first
String b = "world"; --second
a = a + b;          --third (the first is now no longer referenced and would be garbage collectioned by JVM)

在第二种情况下,只2 string objects创建

String a;
String a = "hello";
a = new String("world");

如果您首先使用 StringBuffer 而不是 String,例如

StringBuffer a = new StringBuffer("hello"); --first
String b = "world";                         --second
a.append(b);                                --append to the a
a.append("something more");                 --re-append to the a (after creating a temporary string)

以上只会3 objects在字符串内部连接到同一个对象时创建,同时使用StringBuffer

于 2013-04-04T04:02:05.960 回答
0

在案例 1 中,创建了 3 个对象,“hello”、“world”和“helloworld”

在案例 2 中,在字符串池 "hello" 和 "world" 中创建了两个对象。即使字符串池中有“World”对象,也会创建新的世界对象。

于 2013-04-04T04:03:39.027 回答