繁体   English   中英

Java中的不可变字符串

[英]Immutable string in java

我有基本的困惑。

String s2=new String("immutable");
System.out.println(s2.replace("able","ability"));
s2.replace("able", "abled");
System.out.println(s2);

在第一个打印语句中,它是打印不可变的,但它是不可变的,对吗? 为什么这样? 并且在下一个印刷声明中不替换>欢迎任何答案。

System.out.println(s2.replace("able","ability"));

在上面的行中,返回并打印了一个新字符串。

因为String#replce()

返回一个新字符串,该字符串是用newChar替换此字符串中所有出现的oldChar的结果。

s2.replace("able", "abled");

它执行replace操作,但没有将结果分配回去。因此原始String保持不变。

如果分配结果,则会看到结果。

喜欢

String replacedString = s2.replace("able", "abled");
System.out.println(replacedString );

要么

s2= s2.replace("able", "abled");
System.out.println(s2);

更新:

当你写行

System.out.println(s2.replace("able","ability"));

s2.replace("able","ability")解析并返回String传递给该函数。

replace(String,String)方法返回一个新的String。 第二次对replace()调用返回了替换,但是您没有将其分配给任何东西,然后当再次打印出不可变的s2时,您会看到不变的值。

String#replace返回结果String而不修改原始(不可变) String值...

如果将结果分配给另一个String ,则会得到相同的结果,例如

String s2=new String("immutable");
String s3 = s2.replace("able","ability");
System.out.println(s3);
s2.replace("able", "abled");
System.out.println(s2);

会给你同样的输出...

让我们看一下第2行:

System.out.println(s2.replace("able","ability"));

这将打印不变性,这是因为

s2.replace("able","ability")

将返回另一个字符串,该字符串的输入方式如下:

System.out.println(tempStr);

但是在第三句话中,

s2.replace("able", "abled");

没有分配给另一个变量,因此返回一个字符串,但没有分配给任何变量。 因此丢失了,但是s2保持不变。

Immutable objects are simply objects whose state (the object's data) cannot change after construction

您的代码s2.replace("able","ability") ,它返回一个新的String,而s2没有任何反应。

并且因为replace函数返回一个新的String,所以可以通过System.out.println(s2.replace("able","ability"));打印结果System.out.println(s2.replace("able","ability"));

字符串是不可变的,但是字符串有很多可用作Rvalue

另请参阅

String s2=new String("immutable");

1)每当我们在上面创建一个String时,都会创建一个新对象,如果我们试图对其进行修改,则会使用提供的内容创建一个新对象,并且不会修改String s2。

2)如果我们需要在s2对象中修改值,则将上面的代码替换为..

String s2=new String("immutable");//Creates a new object with content 'immutable'
System.out.println(s2.replace("able","ability"));//creates a new object with new content as //immutability
s2=s2.replace("able", "abled");//Here also it creates a new object,Since we are assigning it //to s2,s2 will be pointing to newly created object.
System.out.println(s2);//prints the s2 String value.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM