JDK源码--StringBuilder/StringBuffer(字符串操作)

11 篇文章 0 订阅

StringBuilder

append

//每个builder有一个默认的value字符数组,append操作都是append到这个数组上
public AbstractStringBuilder append(String str) {
    if (str == null)
        return appendNull();
    int len = str.length();
    ensureCapacityInternal(count + len); //开辟len长度的内测空间
    str.getChars(0, len, value, count); //将str按字符拷贝到当前的value数组中
    count += len;
    return this; 
}

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);
    }
    System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
}

delete

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) {//将原value中start+len开始的count-end个字符拷贝到value的start开始(抹去end - start位置的字符)
        System.arraycopy(value, start+len, value, start, count-end);
        count -= len;
    }
    return this;
}

StringBuffer

append

//实现与StringBuilder类同,唯一不同的是加了synchronized确保线程安全
public synchronized StringBuffer append(String str) {
    toStringCache = null;
    super.append(str);
    return this;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值