如果在此代码中使用方法replace,为什么需要重新定义变量theString
:
String theString = "I w@nt to h@ve the regul@r \"A\"!";
theString = theString.replace("@", "a");
System.out.println(theString);
我为什么不能做:
theString.replace("@", "a");
就是这样吗?
最佳答案
字符串是不可变的-创建字符串后就无法更改它们。当然,如果您使用反射魔术,也有例外,但是在大多数情况下,应将它们视为不变式。因此,方法replace(...)
不会更改String,不能更改String,而是创建并返回新的String。为了能够使用该新String,您必须访问其引用,这可以通过将其分配给String变量甚至是原始String变量来实现。讨论的重点是对象和参考变量之间的区别。