记录一下stringBuilder setCharA(index)报错数组越界SingIndexOutOfBoundsException
StringBuilder res = new StringBuilder(20);
//初始化后会为res分配大小为20的空间,这时按道理res.length()应该等于20吧
System.out.println(res.length()); //打印结果:0
//所以当你执行res.setCharAt(15,'a')的时候报错数组越界,为什么呢,15明明小于20呀
可以看看setCharAt()方法源码:
setCharAt public void setCharAt(int index, char ch) {
if ((index < 0) || (index >= count))
//当index>=count的时候会报错SingIndexOutOfBoundsException
throw new StringIndexOutOfBoundsException(index);
value[index] = ch;
}
再来看看length()方法:
@Override
public int length() { //stringBuilder重写了length方法,返回的是count的值
return count;
}
所以,看了源码就明白stringBuilder使用count来记录字符的长度的
而这个count在初始化的时候=0,当执行new StringBuilder(20)的时候count是不会改变的,改变的是底层数组的大小。
换句话说,stringBulider中用count来记录字符的长度length,而底层分配的空间capacity是数组的内存大小,所以当setCharAt(int index, char ch)中的index虽然小于capacity的值20,但是因为index>字符长度length,所以就会报错
StringBuilder res = new StringBuilder(20);
System.out.println(res.length()); //打印结果:0
System.out.println(res.capacity()); //打印结果:20