对象修改的差异 [英] Differences in Object modifications
问题描述
我只是想知道是否有人可以帮助我解决这个问题:
i was just wondering if anybody could help me out with this :
StringBuilder s=new StringBuilder("0123456789");
s.substring(1, 2);
System.out.println(s);
s.delete(2, 8);
System.out.println(s);
第一个Sysout给出0123456789(尽管我希望有一个子字符串),而其他Sysout给出0189.这种情况s).这与对象的可变性有关吗?有任何一般规则吗? 提前致谢 香港
the first Sysout gives 0123456789(although i expected a substring) but other Sysout gives 0189. I have noticed that also with some Time and Date classes.How can i figure out, when what form is going to modify original object (in this case s). Is this related to Mutability of objects? Is there any general rule? Thanks in advance HK
推荐答案
如果您在AbstractStringBuilder
抽象类中看到了substring
方法定义,后来又由StringBuilder
类扩展了该定义,您将找到以下代码:
If you see the substring
method definition in AbstractStringBuilder
abstract class which later extended by StringBuilder
class, you will find below code:
public String substring(int start, int end) {
if (start < 0)
throw new StringIndexOutOfBoundsException(start);
if (end > count)
throw new StringIndexOutOfBoundsException(end);
if (start > end)
throw new StringIndexOutOfBoundsException(end - start);
return new String(value, start, end - start);
}
从方法定义中可以看到它正在返回一个新的String
对象,该方法不适用于实际的StringBuilder
内容.因此,他们不会更改StringBuilder
对象的内容,而是会返回一个新的String
对象.
From the method definition you can see that it is returning a new String
object, the method is not working on actual StringBuilder
content. So their will no change in the content of StringBuilder
object but rather a new String
object will be returned.
现在,如果您在StringBuilder
类中看到delete
方法定义,则为:
Now if you see delete
method definition inside StringBuilder
class it is:
@Override
public StringBuilder delete(int start, int end) {
super.delete(start, end);
return this;
}
AbstractStringBuilder
(StringBuilder
超类)中delete的定义是:
And the definition of delete in AbstractStringBuilder
(StringBuilder
super class) is :
public AbstractStringBuilder delete(int start, int end) {
if (start < 0)
throw new StringIndexOutOfBoundsException(start);
if (end > count)
end = count;
if (start > end)
throw new StringIndexOutOfBoundsException();
int len = end - start;
if (len > 0) {
System.arraycopy(value, start+len, value, start, count-end);
count -= len;
}
return this;
}
从方法定义中可以清楚地了解到,它正在处理相同的StringBuilder
对象内容,并且它不返回新对象,而是返回传递给它的同一对象引用.
From the method definition it could be clearly understood that it is working on same StringBuilder
object content and it is not returning a new object but rather the same object reference which is passed to it.
这篇关于对象修改的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!