StringBuilder是使用char[] value;存储数据的
@Override
public int length() {
return count;
}
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
长度表示的是字符的个数,容量表示的是可用于最新插入字符的存储量。
例如:
StringBuilder sb=new StringBuilder();
sb.append("666");
sb.setLength(2);
System.out.println(sb.length());//追加了长度为3的字符串,count=count+3,所以结果为3
System.out.println(sb.capacity());//调用父类构造器super(16);即是new char[16],所以结果16
String s=sb.toString();
System.out.println(s);
public void setLength(int newLength) {
if (newLength < 0)
throw new StringIndexOutOfBoundsException(newLength);
ensureCapacityInternal(newLength);
if (count < newLength) {
Arrays.fill(value, count, newLength, ' ');
}
count = newLength;
}
执行sb.setLength(2);char[]数组内容没有变化,下标0,1,2还是存储6,6,6
就是把count值设置为2而已,下面调用toString();方法重新构造一个String对象,char数组存储6,6
如果设置sb.setLength(4);构造新的String对象,最后一个补上'0'。