StringBuilder

StringBuilder


类的声明

public final class StringBuilder
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
  • 继承 AbstractStringBilder 类
    /**
     * The value is used for character storage.
     */
    char[] value;

    /**
     * The count is the number of characters used.
     */
    int count;

构造方法

    /**
     * Constructs a string builder with no characters in it and an
     * initial capacity of 16 characters.
     */
    // 默认构造方法,设置 char[] value 的长度,默认16
    public StringBuilder() {
        super(16);
    }

    /**
     * Constructs a string builder with no characters in it and an
     * initial capacity specified by the <code>capacity</code> argument.
     *
     * @param      capacity  the initial capacity.
     * @throws     NegativeArraySizeException  if the <code>capacity</code>
     *               argument is less than <code>0</code>.
     */
    public StringBuilder(int capacity) {
        super(capacity);
    }

    /**
     * Constructs a string builder initialized to the contents of the
     * specified string. The initial capacity of the string builder is
     * <code>16</code> plus the length of the string argument.
     *
     * @param   str   the initial contents of the buffer.
     * @throws    NullPointerException if <code>str</code> is <code>null</code>
     */
    // 构造参数为字符串,char[] value 的长度为字符串的长度+16
    public StringBuilder(String str) {
        super(str.length() + 16);
        append(str);
    }

    /**
     * Constructs a string builder that contains the same characters
     * as the specified <code>CharSequence</code>. The initial capacity of
     * the string builder is <code>16</code> plus the length of the
     * <code>CharSequence</code> argument.
     *
     * @param      seq   the sequence to copy.
     * @throws    NullPointerException if <code>seq</code> is <code>null</code>
     */
    public StringBuilder(CharSequence seq) {
        this(seq.length() + 16);
        append(seq);
    }

append()

    // 调用 append 方法
    public StringBuilder append(String str) {
        super.append(str);
        return this;
    }

    // 调用父类 AbstractStringBuilder 中 append 方法
    public AbstractStringBuilder append(String str) {
    // 如果添加的字符串为null,实际添加 "null" 而不是不做处理
        if (str == null) str = "null";
        // 添加的字符串的长度
        int len = str.length();
        // 字符串长度 + 现有 char[] 的字符个数 count  是否大于 char[] 的长度
        // 是否需要扩充容量
        ensureCapacityInternal(count + len);
        // 字符串拷贝,append 方法每次调用将参数str放到已有字符串的后面,原理在于
        // value (指已有的字符数据 char[] values) 从 count 位置开始 ; 将 str 的 0 ~ len 的长度的内容拷贝过去
        str.getChars(0, len, value, count);
        // 当前 char[] value 的长度变更
        count += len;
        return this;
    }

    // 上述方法调用 String 的 getChars 方法
    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);
        }
        // native 方法
        // 在 dst 的 dstBegin 位置开始拷贝 value 从 srcBegin 的开始长度为 srcEnd - srcBegin 的内容
        System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }

    // count 是 char[] value 中字符的个数
    // len 是当前添加的字符串 str 的长度
    // value.length 是 char[] value 的长度,即数组的容量
    private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        // 如果添加的字符串的长度超过了数据中剩余的空间,则会扩容
        if (minimumCapacity - value.length > 0)
            expandCapacity(minimumCapacity);
    }

    /**
     * This implements the expansion semantics of ensureCapacity with no
     * size check or synchronization.
     */
    void expandCapacity(int minimumCapacity) {
    // 扩容: *2 + 2
        int newCapacity = value.length * 2 + 2;
        // 扩容后依然小于 count + len ,则直接扩容至 count + len
        if (newCapacity - minimumCapacity < 0)
            newCapacity = minimumCapacity;
        // count + len 是 int 类型,最大值为 Integer.MAX_VALUE 
        // 如果超过了最大值,则会发生溢出 overflow
        if (newCapacity < 0) {
            if (minimumCapacity < 0) // overflow
                throw new OutOfMemoryError();
            newCapacity = Integer.MAX_VALUE;
        }
        value = Arrays.copyOf(value, newCapacity);
    }

    // 调用 Arrasys copyOf 方法
    public static char[] copyOf(char[] original, int newLength) {
    // 此处可能发生 java.lang.OutOfMemoryError: Java heap space
    // 数组的最大长度不是无限设置的,数组的length为int类型,最大上限于 Integer.MAX_VALUE 有关,数组带下同时需要考虑 JVM 的配置
        char[] copy = new char[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

参考资料

小学徒成长系列—StringBuilder & StringBuffer关键源码解析

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值