【问题标题】:String class replace() method [closed]字符串类替换()方法[关闭]
【发布时间】:2013-07-30 05:36:58
【问题描述】:

这段代码sn-p创建了多少个Object?

String x = "xyz"; // #1
x.toUpperCase(); /* Line 2 */ #2
String y = x.replace('Y', 'y'); //Will here new object is created or not?
y = y + "abc"; // #3 ?
System.out.println(y);

三个。我想..?

【问题讨论】:

  • ...第 3 行呢?
  • 将语言标签添加到您的问题中。爪哇?
  • 如果是 Java,字符串是不可变的,所以会在替换行中创建另一个对象

标签: java string immutability


【解决方案1】:

创建了多少对象?

// "xyz" is interned , JVM will create this object and keep it in String pool
String x = "xyz";
// a new String object is created here , x still refers to "xyz" 
x.toUpperCase(); 
// since char literal `Y` is not present in String referenced by x ,
// it returns the same instance referenced by x 
String y = x.replace('Y', 'y'); 
//  "abc" was interned and y+"abc" is a new object
y = y + "abc";  
System.out.println(y);

此语句返回对同一字符串对象x的引用:

String y = x.replace('Y', 'y'); 

documentation

如果此String对象表示的字符序列中没有出现oldChar字符,则返回对该String对象的引用。否则,创建一个表示字符序列的新String对象与此 String 对象表示的字符序列相同,只是每次出现的 oldChar 都替换为出现的 newChar。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-08
    • 2012-09-25
    • 2022-06-10
    • 2014-10-29
    • 1970-01-01
    相关资源
    最近更新 更多