如果您看到substring
方法定义在AbstractStringBuilder
抽象类,后来扩展为StringBuilder
类,你会发现下面的代码:
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
对象将被返回。
现在如果你看到delete
里面的方法定义StringBuilder
类是:
@Override
public StringBuilder delete(int start, int end) {
super.delete(start, end);
return this;
}
以及删除的定义AbstractStringBuilder
(StringBuilder
超类)是:
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
对象内容,并且它不返回新对象,而是返回传递给它的相同对象引用。