【问题标题】:String object creation字符串对象创建
【发布时间】:2013-03-25 23:46:50
【问题描述】:

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

案例一:

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

案例 2:

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

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

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

【问题讨论】:

  • 以前的帖子讨论过这个stackoverflow.com/questions/3297867/…
  • 您可以轻松获得很多关于这个主题的教程和文章,它们非常清楚地解释了每一件事。不要问如此愚蠢的问题,因为您只需在谷歌上一击即可轻松获得答案。做好功课,诚实做事,有问题欢迎提出问题。我没有足够的声誉分数来投票否决或关闭它。不要指望用勺子喂食。

标签: java string object immutability stringbuffer


【解决方案1】:

正如您正确提到的字符串是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

【讨论】:

  • 我不知道你为什么会回答这样的问题......但干得好。不要指望 OP 投票或选择这个答案。他会阅读32,将它们添加到他的家庭作业中,然后再也不会收到消息了!
  • Akash,据我所知,JVM 不允许在字符串池(SCP 区域)内进行垃圾收集。只有当整个 JVM 关闭时,所有字符串才会被销毁。如果我错了,请告诉我。
  • ^^ 同意。当字符串被创建为文字时,它们的处理方式不同(在这种情况下不是 GC)。另外,在您的第三个示例中,我相信创建了 3 个字符串: 1.) "hello" 2.) "world" 3.) "更多”
  • @ShaileshSaxena 对,不知道我是怎么错过那个的:p
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-08
      • 2014-11-22
      • 2014-12-23
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多