字符串不变性
有人告诉我java中的字符串不能改变。下面的代码怎么样?
name="name";
name=name.replace('a', 'i');
它不会改变 name
字符串吗? 另外,replace()的实现在哪里;比较();等于();假如? 我只是在这里使用这些功能,但它们实际上是在哪里实现的呢?
I was told that strings in java can not be changed.What about the following code?
name="name";
name=name.replace('a', 'i');
Does not it changes name
string?
Also, where is the implementation of the replace(); compareTo(); equals(); provided?
I am just using these functions here, but where actually are they implemented?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
String.replace() 返回一个新字符串。
“name”是对 String 对象的引用,因此可以将其重新分配为指向 name.replace(),但它将指向一个新对象。
这是 String 的 javadoc,您可以在其中可以找出所有方法的作用。
String.replace() returns a new String.
"name" is a reference to a String object, so it can be reassigned to point to name.replace(), but it will be pointing to a new object.
Here is the javadoc for String, where you can find out what all the methods do.
这是一个将引用变量(名称)与其引用的 String 对象(“名称”)混淆的典型案例。他们是两种截然不同的野兽。字符串永远不会改变(忽略反射类型拼凑),但引用变量可以根据需要引用任意多个不同的字符串。您会注意到,如果您只是打电话,
什么也不会发生。仅当您将 name 变量分配给不同的字符串(由
replace
方法返回的字符串)时,您才能看到更改。This is a classic case of confusing a reference variable (name) with a String object it refers to ("name"). They are two very different beasts. The String never changes (ignoring reflection type kludges), but a reference variable can refer to as many different Strings as needed. You will notice that if you just called
nothing happens. You only can see a change if you have your name variable assigned to a different String, the one returned by the
replace
method.尝试一下并亲眼看看:
如果将新的引用分配给 r,原始对象将不会改变。
我希望这有帮助。
Try this and see it for your self:
If you assign the new ref to r, the original object wont change.
I hope this helps.
如果你的代码是
<代码>
名称=“名称”;
名称.replace('a', 'i'); //忽略对字符串变量名的赋值
System.out.print(name)
输出:
<代码>
name
这是因为
name.replace('a','i')
会将替换的字符串nime
放入字符串池中,但引用不指向字符串变量名。每当你尝试修改字符串对象时,
java 检查结果字符串在字符串池中是否可用
如果可用,则可用字符串的引用指向字符串变量
否则,在字符串池中创建新的字符串对象,并将创建的对象的引用指向字符串变量。If your code is
name="name";
name.replace('a', 'i'); //assignment to String variable name is neglected
System.out.print(name)
output:
name
this is because the
name.replace('a','i')
would have put the replaced string,nime
in the string pool but the reference is not pointed to String variable name.Whenever u try to modify a string object,
java checks, is the resultant string is available in the string pool
if available the reference of the available string is pointed to the string variable
else new string object is created in the string pool and the reference of the created object is pointed to the string variable.