记录一下stringBuilder setCharA(index)报错数组越界SingIndexOutOfBoundsException

记录一下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
  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值