版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ytlviv1985/article/details/83186542
无聊拔码看了这个类
1.先看setLength,简单就是将count直接赋值为0,但是value没有任何清除
public void setLength(int newLength) {
if (newLength < 0)
throw new StringIndexOutOfBoundsException(newLength);
ensureCapacityInternal(newLength);
if (count < newLength) {
Arrays.fill(value, count, newLength, '\0');
}
count = newLength;
}
我们setLength(0)后在append的时候操作
public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull();
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count); // 此时count为0 len为当前插入串的长度
count += len; // 重新标记count 在toString的时候从value的0到count的位置取出数据
return this;
}
在看string 类的getChars
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
if (srcBegin < 0) {
throw new StringIndexOutOfBoundsException(srcBegin);
}
if (srcEnd > value.length) {
throw new StringIndexOutOfBoundsException(srcEnd);
}
if (srcBegin > srcEnd) {
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
}
// 将插入字符串拷贝到stringBuffer的value,这里是0开始
System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
}
2.delete操作 delete(0,len)
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) {
// delete 操作立马回拷贝数组,比setlength多一个拷贝操作
System.arraycopy(value, start+len, value, start, count-end);
count -= len;
}
return this;
}
所以setlength会比delete少一次System.arraycopy