AbstractStringBuilder源码分析

 AbstractStringBuilder这个源码很有必要看,StringBuffer, StringBuilder都是实现的这个类,它们中的方法也是调用的这个类的方法。

StringBuilder源码分析:https://blog.csdn.net/qq_26896085/article/details/95942895

StrijngBuffer源码分析:https://blog.csdn.net/qq_26896085/article/details/95966568

package java.lang;
import sun.misc.FloatingDecimal;
import java.util.Arrays;

// AbstractStringBuilder 是抽象类,不能被实例化
abstract class AbstractStringBuilder implements Appendable, CharSequence {
    // 定义字符数组用来接收传入的字符串
    char[] value;
    // 字符串或字符数组的实际大小
    int count;
    
    // 构造函数
    AbstractStringBuilder() {
    }
    // 构造函数
    AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }
    
    // 计算长度
    @Override
    public int length() {
        return count;
    }
    
    // 计算容量
    public int capacity() {
        return value.length;
    }
    
    // 确保有容量,传入参数minimumCapacity,如果minimumCapacity>容量,就进行扩容
    public void ensureCapacity(int minimumCapacity) {
        if (minimumCapacity > 0)
            ensureCapacityInternal(minimumCapacity);
    }
    
    // 确保有容量,传入参数minimumCapacity,如果minimumCapacity>value.length,就进行扩容
    private void ensureCapacityInternal(int minimumCapacity) {
        // 如果传入的容量比较当前的容量大,那么就进行掂量,否则不扩容
        if (minimumCapacity - value.length > 0) {
            // 扩容,将当前的数据复制到新的数组里面
            value = Arrays.copyOf(value,
                    newCapacity(minimumCapacity));
        }
    }
    
    // 最大的容量
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    
    // 新的容量
    private int newCapacity(int minCapacity) {
        // 扩容的规则,原来容量*2+2
        int newCapacity = (value.length << 1) + 2;
        // 新的容量<最小的容量,那么将最小的容量赋值给新的容量
        if (newCapacity - minCapacity < 0) {
            newCapacity = minCapacity;
        }
        // 判断新的容量是否为负(超过最大的容量+8?),或超过最大的容量
        // 是就将
        return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
            ? hugeCapacity(minCapacity)
            : newCapacity;
    }
    
    // 返回最大容量
    private int hugeCapacity(int minCapacity) {
        
        if (Integer.MAX_VALUE - minCapacity < 0) { // overflow
            throw new OutOfMemoryError();
        }
        // minCapacity是否大于最大的MAX_ARRAY_SIZE, 是返回min.. 还是返回 MAX_ARRAY_SIZE
        // 反正就是返回一个最大的容量
        return (minCapacity > MAX_ARRAY_SIZE)
            ? minCapacity : MAX_ARRAY_SIZE;
    }
    
    // 减少字符序列的存储
    public void trimToSize() {
        // 减少容量?
        if (count < value.length) {
            value = Arrays.copyOf(value, count);
        }
    }
    
    // 设置长度
    public void setLength(int newLength) {
        // 设置的长度不能小于-
        if (newLength < 0)
            throw new StringIndexOutOfBoundsException(newLength);
        // 将容量newLength给新的数组设置上,是否扩容看newLength的大小
        ensureCapacityInternal(newLength);
        // count < newLength说明已经扩容
        if (count < newLength) {
            // 将数据设置给新的容量数组
            Arrays.fill(value, count, newLength, '\0');
        }
        count = newLength;
    }
    
    // 给定下标获取字符串
    @Override
    public char charAt(int index) {
        // 判定下标的范围 ,抛异常
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        return value[index];
    }
    
    // 返回指定索引处的字符的编码
    public int codePointAt(int index) {
        // 判定下标的范围 ,抛异常
        if ((index < 0) || (index >= count)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        // 获取到value[index]位置的字符编码
        return Character.codePointAtImpl(value, index, count);
    }

    // 获取到value[index]前面一位的字符编码,即value[--index]的字符编码
    public int codePointBefore(int index) {
        int i = index - 1;
        if ((i < 0) || (i >= count)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return Character.codePointBeforeImpl(value, index, 0);
    }
    
    // 计算beginIndex与endIndex索引之间字符的数量,[beginIndex, endIndex),
    public int codePointCount(int beginIndex, int endIndex) {
        if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) {
            throw new IndexOutOfBoundsException();
        }
        return Character.codePointCountImpl(value, beginIndex, endIndex-beginIndex);
    }
    
    // 返回偏移位置的字符,返回value[(index+codePointOffset)]
    public int offsetByCodePoints(int index, int codePointOffset) {
        if (index < 0 || index > count) {
            throw new IndexOutOfBoundsException();
        }
        return Character.offsetByCodePointsImpl(value, 0, count,
                                                index, codePointOffset);
    }
    /**
     * 将字符串中的数据复制到dst中
     * @param srcBegin 字符串中开始的下标
     * @param srcEnd 字符串中结束的下标
     * @param dst 将字符串中的字符串复制到dst中
     * @param dstBegin dst中接收字符开始的位置
     */
    //**
    public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
    {
        if (srcBegin < 0)
            throw new StringIndexOutOfBoundsException(srcBegin);
        if ((srcEnd < 0) || (srcEnd > count))
            throw new StringIndexOutOfBoundsException(srcEnd);
        if (srcBegin > srcEnd)
            throw new StringIndexOutOfBoundsException("srcBegin > srcEnd");
        System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }
    // 将指定位置的数据设置上给定的字符
    public void setCharAt(int index, char ch) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        value[index] = ch;
    }
    
    // 在字符串的末尾添加obj
    public AbstractStringBuilder append(Object obj) {
        return append(String.valueOf(obj));
    }
    
    // 将String字符串添加 到末尾
    public AbstractStringBuilder append(String str) {
        if (str == null)
            return appendNull();
        int len = str.length();
        // 进行扩容操作
        ensureCapacityInternal(count + len);
        // 这里传入的count为value中有效字符数量,count作为下标时,刚好为有效字符下标的后一位
        // 意思是将sb中的字符复制到value中,这里通过下标count控制sb传入到value的位置,
        //      刚好可以将sb中的数据添加到原来数据的后面
        str.getChars(0, len, value, count);
        count += len;
        return this;
    }

    // 将StringBuffer字符串添加 到末尾
    public AbstractStringBuilder append(StringBuffer sb) {
        if (sb == null)
            return appendNull();
        int len = sb.length();
        // 进行扩容操作
        ensureCapacityInternal(count + len);
        // 这里传入的count为value中有效字符数量,count作为下标时,刚好为有效字符下标的后一位
        // 意思是将sb中的字符复制到value中,这里通过下标count控制sb传入到value的位置,
        //      刚好可以将sb中的数据添加到原来数据的后面
        sb.getChars(0, len, value, count);
        count += len;
        return this;
    }
    
    // 将AbstractStringBuilder字符串添加 到末尾
    // 这里StringBuilder与StringBuffer都是继承的AbstractStringBuilder,这里与上面这个有什么区别?
    AbstractStringBuilder append(AbstractStringBuilder asb) {
        if (asb == null)
            return appendNull();
        int len = asb.length();
        // 进行扩容操作
        ensureCapacityInternal(count + len);
        // 这里传入的count为value中有效字符数量,count作为下标时,刚好为有效字符下标的后一位
        // 意思是将sb中的字符复制到value中,这里通过下标count控制sb传入到value的位置,
        //      刚好可以将sb中的数据添加到原来数据的后面
        asb.getChars(0, len, value, count);
        count += len;
        return this;
    }

    // 添加到末尾,传入一个CharSequence
    @Override
    public AbstractStringBuilder append(CharSequence s) {
        if (s == null)
            return appendNull();
        if (s instanceof String)
            return this.append((String)s);
        if (s instanceof AbstractStringBuilder)
            return this.append((AbstractStringBuilder)s);
        return this.append(s, 0, s.length());
    }
    
    // 传入的数据为空时,将null添加到其末尾
    private AbstractStringBuilder appendNull() {
        int c = count;
        ensureCapacityInternal(c + 4);
        final char[] value = this.value;
        value[c++] = 'n';
        value[c++] = 'u';
        value[c++] = 'l';
        value[c++] = 'l';
        count = c;
        return this;
    }
    
    // 将字符序列s,添加到value的后面
    @Override
    public AbstractStringBuilder append(CharSequence s, int start, int end) {
        if (s == null)
            s = "null";
        if ((start < 0) || (start > end) || (end > s.length()))
            throw new IndexOutOfBoundsException(
                "start " + start + ", end " + end + ", s.length() "
                + s.length());
        int len = end - start;
        // 扩容
        ensureCapacityInternal(count + len);
        // 添加
        for (int i = start, j = count; i < end; i++, j++)
            value[j] = s.charAt(i);
        count += len;
        return this;
    }
    
    // 将字符数组添加到value的后面
    public AbstractStringBuilder append(char[] str) {
        int len = str.length;
        // 扩容
        ensureCapacityInternal(count + len);
        // 将str复制到value中,len是value的接收字符的开始位置
        System.arraycopy(str, 0, value, count, len);
        count += len;
        return this;
    }
    
    // 将字符数组添加到value的后面,指定str的开始位置与结束位置
    public AbstractStringBuilder append(char str[], int offset, int len) {
        if (len > 0)
            ensureCapacityInternal(count + len);
        System.arraycopy(str, offset, value, count, len);
        count += len;
        return this;
    }
    
    // 将boolean数据添加到value的后面
    public AbstractStringBuilder append(boolean b) {
        if (b) {
            ensureCapacityInternal(count + 4);
            value[count++] = 't';
            value[count++] = 'r';
            value[count++] = 'u';
            value[count++] = 'e';
        } else {
            ensureCapacityInternal(count + 5);
            value[count++] = 'f';
            value[count++] = 'a';
            value[count++] = 'l';
            value[count++] = 's';
            value[count++] = 'e';
        }
        return this;
    }

    // 将字符c添加到value的后面
    @Override
    public AbstractStringBuilder append(char c) {
        // 扩容
        ensureCapacityInternal(count + 1);
        value[count++] = c;
        return this;
    }
    
    // 将数字i,添加到value的后面
    public AbstractStringBuilder append(int i) {
        if (i == Integer.MIN_VALUE) {
            append("-2147483648");
            return this;
        }
        // 计算i的长度
        int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
                                     : Integer.stringSize(i);
        // 计算一共需要的长度
        int spaceNeeded = count + appendedLength;
        // 扩容
        ensureCapacityInternal(spaceNeeded);
        // 因为前面的spaceNeeded已经计算好了已有字符串+value的长度,因此这里可以刚好将数字放到value中,
        Integer.getChars(i, spaceNeeded, value);
        count = spaceNeeded;
        return this;
    }
    
    // 将长整型数据添加 到value的后面
    public AbstractStringBuilder append(long l) {
        if (l == Long.MIN_VALUE) {
            append("-9223372036854775808");
            return this;
        }
        // 计算l的长度, 
        int appendedLength = (l < 0) ? Long.stringSize(-l) + 1
                                     : Long.stringSize(l);
        // 计算一共需要的长度
        int spaceNeeded = count + appendedLength;
        //扩容
        ensureCapacityInternal(spaceNeeded);
        // 因为前面的spaceNeeded已经计算好了已有字符串+value的长度,因此这里可以刚好将数字放到value中
        Long.getChars(l, spaceNeeded, value);
        count = spaceNeeded;
        return this;
    }
    
    // 将 小数类型的数据添加到value的后面
    public AbstractStringBuilder append(float f) {
        FloatingDecimal.appendTo(f,this);
        return this;
    }
    public AbstractStringBuilder append(double d) {
        FloatingDecimal.appendTo(d,this);
        return this;
    }
    
    // 删除字符串中指定位置的数据[start, end)
    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) {
            // len = end - start --> start + len = end 
            // System.arraycopy(value1, end, value2, start, count-end);
            // 从value1中从end下标开始复制count-end个字符到value2中,从value2的start下标开始存放
            System.arraycopy(value, start+len, value, start, count-end);
            count -= len;
        }
        return this;
    }
    
    // 将codePoint参数的字符串表示附加到此序列
    public AbstractStringBuilder appendCodePoint(int codePoint) {
        final int count = this.count;
        // 判断传入的codePoint的范围
        if (Character.isBmpCodePoint(codePoint)) {
            // 传入一个字符是否需要进行扩容
            ensureCapacityInternal(count + 1);
            // 转换成char后连接到value的后面
            value[count] = (char) codePoint;
            this.count = count + 1;
        } else if (Character.isValidCodePoint(codePoint)) {
            // char占用两个字节
            ensureCapacityInternal(count + 2);
            // 将codePoint转换成对应的字符,放入到value中
            Character.toSurrogates(codePoint, value, count);
            this.count = count + 2;
        } else {
            throw new IllegalArgumentException();
        }
        return this;
    }
    
    // 根据传入的下标删除对应的字符串中的字符
    public AbstractStringBuilder deleteCharAt(int index) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        // value --> 0,1,2,3,4,5,6,7,8,9
        // index = 3,  -->  count - index -1 = 6  -->  复制的个数为6 即 456789
        // 将第一个value中的456789复制到第二个value中
        // 第二个value中 index = 3, 从value下标为3开始将456789放入value中,012保留 --> 012456789 
        System.arraycopy(value, index+1, value, index, count-index-1);
        count--;
        return this;
    }
    
    // 用指定的str替换字符串中的下标为[start, end)的数据
    public AbstractStringBuilder replace(int start, int end, String str) {
        // 对传入的数据进行校验,抛异常
        if (start < 0)
            throw new StringIndexOutOfBoundsException(start);
        if (start > count)
            throw new StringIndexOutOfBoundsException("start > length()");
        if (start > end)
            throw new StringIndexOutOfBoundsException("start > end");
        
        if (end > count)
            end = count;
        int len = str.length();
        // 计算新的字符串的长度
        int newCount = count + len - (end - start);
        // 是否需要进行扩容
        ensureCapacityInternal(newCount);
        // 将第一个value中end以后的数据拷贝到第二个value中
        System.arraycopy(value, end, value, start + len, count - end);
        // 将str复制到value中
        str.getChars(value, start);
        count = newCount;
        return this;
    }
    
    // 字符串的截取,
    public String substring(int start) {
        // 传入开始的位置,默认截取到最后
        return substring(start, count);
    }
    
    // 字符序列的截取
    @Override
    public CharSequence subSequence(int start, int end) {
        return substring(start, end);
    }
    
    // 字符串的截取,并指定截取的起始位置
    public String substring(int start, int end) {
        if (start < 0)
            throw new StringIndexOutOfBoundsException(start);
        if (end > count)
            throw new StringIndexOutOfBoundsException(end);
        if (start > end)
            throw new StringIndexOutOfBoundsException(end - start);
        // 调用String指定传入字符串的起始位置,返回一个新的String
        return new String(value, start, end - start);
    }
    
    // 将char中len个数据插入到value中
    public AbstractStringBuilder insert(int index, char[] str, int offset,
                                        int len)
    {
        if ((index < 0) || (index > length()))
            throw new StringIndexOutOfBoundsException(index);
        if ((offset < 0) || (len < 0) || (offset > str.length - len))
            throw new StringIndexOutOfBoundsException(
                "offset " + offset + ", len " + len + ", str.length "
                + str.length);
        // 插入len长度的字符后是否需要进行扩容
        ensureCapacityInternal(count + len);
        // 将value中下标为index以后的数据拷贝到第二个value中,第二个value的起始下标为index+len
        System.arraycopy(value, index, value, index + len, count - index);
        // 将str中的数据拷贝到value,中位置为[index, len)
        System.arraycopy(str, offset, value, index, len);
        count += len;
        return this;
    }
    
    // 将object插入到value中
    public AbstractStringBuilder insert(int offset, Object obj) {
        // obj转换成了String
        return insert(offset, String.valueOf(obj));
    }
    
    // 将字符串插入到当前字符串的offset位置
    public AbstractStringBuilder insert(int offset, String str) {
        if ((offset < 0) || (offset > length()))
            throw new StringIndexOutOfBoundsException(offset);
        if (str == null)
            str = "null";
        int len = str.length();
        // 是否需要扩容
        ensureCapacityInternal(count + len);
        // 将第一个value中offset下标及以后的字符插入到valueoffset下标及以后
        System.arraycopy(value, offset, value, offset + len, count - offset);
        // 将str插入到value的offse位置
        str.getChars(value, offset);
        count += len;
        return this;
    }
    
    // 将字符数组插入到当前字符串的offset位置
    public AbstractStringBuilder insert(int offset, char[] str) {
        if ((offset < 0) || (offset > length()))
            throw new StringIndexOutOfBoundsException(offset);
        int len = str.length;
        // 是否需要进行扩容
        ensureCapacityInternal(count + len);
        System.arraycopy(value, offset, value, offset + len, count - offset);
        // 将str插入到value的offse位置
        System.arraycopy(str, 0, value, offset, len);
        count += len;
        return this;
    }
    
    // 将字符序列插入到当前字符串的offset位置
    public AbstractStringBuilder insert(int dstOffset, CharSequence s) {
        if (s == null)
            s = "null";
        if (s instanceof String)
            // 如果是String则调用前面的方法
            return this.insert(dstOffset, (String)s);
        return this.insert(dstOffset, s, 0, s.length());
    }
    
    // 将字符序列插入到当前字符的dstOffset位置,指定字符序列的插入的起始位置
    public AbstractStringBuilder insert(int dstOffset, CharSequence s,
                                         int start, int end) {
        // 校验数据,是否抛异常
        if (s == null)
            s = "null";
        if ((dstOffset < 0) || (dstOffset > this.length()))
            throw new IndexOutOfBoundsException("dstOffset "+dstOffset);
        if ((start < 0) || (end < 0) || (start > end) || (end > s.length()))
            throw new IndexOutOfBoundsException(
                "start " + start + ", end " + end + ", s.length() "
                + s.length());
        
        int len = end - start;
        // 是否进行扩容
        ensureCapacityInternal(count + len);
        // 将第一个value中dstOffset下标及以后的字符复制到第二value的dstOffset+len下标及以后的位置
        // 这里为value中留下了len的位置去接收s中的数据
        System.arraycopy(value, dstOffset, value, dstOffset + len,
                         count - dstOffset);
        // 将s中的数据放入到value中
        for (int i=start; i<end; i++)
            value[dstOffset++] = s.charAt(i);
        count += len;
        return this;
    }
    
    // 将boolean数据插入到当前字符串的指定的位置,指定的下标为offset
    public AbstractStringBuilder insert(int offset, boolean b) {
        return insert(offset, String.valueOf(b));
    }
    // 将字符插入到当前的字符串的指定的位置,指定的位置为offset
    public AbstractStringBuilder insert(int offset, char c) {
        ensureCapacityInternal(count + 1);
        System.arraycopy(value, offset, value, offset + 1, count - offset);
        value[offset] = c;
        count += 1;
        return this;
    }
    
    // 将数字类型的数据放入到当前的字符串的指定的位置,底层都是将其转换成字符串后,再调用insert(int, String)
    public AbstractStringBuilder insert(int offset, int i) {
        return insert(offset, String.valueOf(i));
    }
    public AbstractStringBuilder insert(int offset, long l) {
        return insert(offset, String.valueOf(l));
    }
    public AbstractStringBuilder insert(int offset, float f) {
        return insert(offset, String.valueOf(f));
    }
    public AbstractStringBuilder insert(int offset, double d) {
        return insert(offset, String.valueOf(d));
    }
    
    // 返回字符串在当前字符串中第一次出现的位置
    public int indexOf(String str) {
        return indexOf(str, 0);
    }
    // 返回字符串在当前字符串中指定下标以后,第一次出现的位置
    public int indexOf(String str, int fromIndex) {
        return String.indexOf(value, 0, count, str, fromIndex);
    }
    // 返回字符串在当前字符串的最后一次出现的位置
    public int lastIndexOf(String str) {
        return lastIndexOf(str, count);
    }
    // 返回字符串在当前字符串中指定下标之前最后一次出现的位置
    public int lastIndexOf(String str, int fromIndex) {
        return String.lastIndexOf(value, 0, count, str, fromIndex);
    }
    
    // 将字符串反转
    public AbstractStringBuilder reverse() {
        boolean hasSurrogates = false;
        int n = count - 1;
        for (int j = (n-1) >> 1; j >= 0; j--) {
            int k = n - j;
            // 定义两个临时变量用来接收,
            char cj = value[j];
            char ck = value[k];
            // 对应位置数据的交换
            value[j] = ck;
            value[k] = cj;
            if (Character.isSurrogate(cj) ||
                Character.isSurrogate(ck)) {
                hasSurrogates = true;
            }
        }
        if (hasSurrogates) {
            reverseAllValidSurrogatePairs();
        }
        return this;
    }

    private void reverseAllValidSurrogatePairs() {
        for (int i = 0; i < count - 1; i++) {
            char c2 = value[i];
            if (Character.isLowSurrogate(c2)) {
                char c1 = value[i + 1];
                if (Character.isHighSurrogate(c1)) {
                    value[i++] = c1;
                    value[i] = c2;
                }
            }
        }
    }

    @Override
    public abstract String toString();
    
    // 
    final char[] getValue() {
        return value;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值