JDK源码之——AbstractStringBuilder

部分方法没有解释,有疑问或错误的地方,欢迎评论指出

import sun.misc.FloatingDecimal;

import java.util.Arrays;

ort javtil.Arrays;

/**
 * StringBuilder 抽象类
 */
abstract class AbstractStringBuilder implements Appendable, CharSequence {
    /**
     * 储存值的数组
     */
    char[] value;

    /**
     * 容量大小
     */
    int count;

    /**
     * 无参构造
     */
    AbstractStringBuilder() {
    }

    /**
     * 根据传入长度构造 AbstractStringBuilder
     */
    AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }

    /**
     * 返回字符串长度 (字符数)
     */
    @Override
    public int length() {
        return count;
    }

    /**
     * 返回当前容量
     */
    public int capacity() {
        return value.length;
    }

    /**
     * 确保容量足够
     */
    public void ensureCapacity(int minimumCapacity) {
        if (minimumCapacity > 0)
            ensureCapacityInternal(minimumCapacity);
    }

    // 判断传入容量是否超过容量 超过则扩容
    private void ensureCapacityInternal(int minimumCapacity) {

        if (minimumCapacity - value.length > 0)
            expandCapacity(minimumCapacity);
    }

    /**
     * 扩容
     */
    void expandCapacity(int minimumCapacity) {
        //一次长度为length + 2
        int newCapacity = value.length * 2 + 2;
        //如果扩容一次还不足minimumCapacity,则取minimumCapacity
        if (newCapacity - minimumCapacity < 0)
            newCapacity = minimumCapacity;
        //如果newCapacity还小于0 , 则取Integer所支持的最大值
        if (newCapacity < 0) {
            if (minimumCapacity < 0) // overflow
                throw new OutOfMemoryError();
            newCapacity = Integer.MAX_VALUE;
        }
        //复制数组的值 到新的数组中,新的数组长度为newCapacity
        value = Arrays.copyOf(value, newCapacity);
    }

    /**
     * 尝试减少value所占用的存储空间。
     * 如果缓冲区 length 大于保持其当前序列所需的缓冲区字符 count ,
     * 则调整value的大小以提高空间效率
     */
    public void trimToSize() {
        if (count < value.length) {
            value = Arrays.copyOf(value, count);
        }
    }

    //设置value数组新长度
    public void setLength(int newLength) {
        if (newLength < 0)
            throw new StringIndexOutOfBoundsException(newLength);
        //确保容量
        ensureCapacityInternal(newLength);

        if (count < newLength) {
            // 将指定的 Object 引用分配 给 指定 Object 数组指定范围中的每个元素。
            // 填充的范围从索引 fromIndex(包括)一直到索引 toIndex(不包括)。
            //(如果 fromIndex==toIndex,则填充范围为空。)
            // fill(Object[] a, int fromIndex, int toIndex, Object val)
            Arrays.fill(value, count, newLength, '\0');// 空字符(NUL) 、 ASCII码值 000
        }
        count = newLength;
    }

    /**
     * 返回指定位置的字符串
     */
    @Override
    public char charAt(int index) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        return value[index];
    }

    //复制数组
    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);
    }

    //在指定位置插入char
    public void setCharAt(int index, char ch) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        value[index] = ch;
    }

    //append
    public AbstractStringBuilder append(Object obj) {
        return append(String.valueOf(obj));
    }

    //append字符串,添加字符串
    public AbstractStringBuilder append(String str) {
        if (str == null)
            //添加空 则添加"null"
            return appendNull();
        int len = str.length();
        //确保容量
        ensureCapacityInternal(count + len);
        //复制数组
        str.getChars(0, len, value, count);
        //容量同步
        count += len;
        return this;
    }

    // Documentation in subclasses because of synchro difference
    public AbstractStringBuilder append(StringBuffer sb) {
        if (sb == null)
            return appendNull();
        int len = sb.length();
        ensureCapacityInternal(count + len);
        sb.getChars(0, len, value, count);
        count += len;
        return this;
    }

    /**
     * 从1.8新增
     * @since 1.8
     */
    AbstractStringBuilder append(AbstractStringBuilder asb) {
        if (asb == null)
            return appendNull();
        int len = asb.length();
        ensureCapacityInternal(count + len);
        asb.getChars(0, len, value, count);
        count += len;
        return this;
    }

    // Documentation in subclasses because of synchro difference
    @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" count
    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;
    }

    //添加 固定长度字符
    @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
            value[j] = s.charAt(i);
        count += len;
        return this;
    }

    //添加boolean值
    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;
    }

    //添加单个字符
    @Override
    public AbstractStringBuilder append(char c) {
        ensureCapacityInternal(count + 1);
        value[count++] = c;
        return this;
    }

    //添加整数
    public AbstractStringBuilder append(int i) {
        if (i == Integer.MIN_VALUE) {
            append("-2147483648");
            return this;
        }
        int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
                : Integer.stringSize(i);
        int spaceNeeded = count + appendedLength;
        ensureCapacityInternal(spaceNeeded);
        Integer.getChars(i, spaceNeeded, value);
        count = spaceNeeded;
        return this;
    }

    //添加long型数据
    public AbstractStringBuilder append(long l) {
        if (l == Long.MIN_VALUE) {
            append("-9223372036854775808");
            return this;
        }
        int appendedLength = (l < 0) ? Long.stringSize(-l) + 1
                : Long.stringSize(l);
        int spaceNeeded = count + appendedLength;
        ensureCapacityInternal(spaceNeeded);
        Long.getChars(l, spaceNeeded, value);
        count = spaceNeeded;
        return this;
    }

    //删除指定间隔中的字符
    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) {
            System.arraycopy(value, start+len, value, start, count-end);
            count -= len;
        }
        return this;
    }

    /**
     * 删除指定位置的字符
     * @param index
     * @return
     */
    public AbstractStringBuilder deleteCharAt(int index) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        //数组拷贝
        System.arraycopy(value, index+1, value, index, count-index-1);
        count--;
        return this;
    }

    //字符替换
    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);
        //数组拷贝
        System.arraycopy(value, end, value, start + len, count - end);
        str.getChars(value, start);
        count = newCount;
        return this;
    }

    //字符串截取 开始位置到最后位置
    public String substring(int start) {
        return substring(start, count);
    }

    //字符串截取 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);
        return new String(value, start, end - start);
    }


    @Override
    public abstract String toString();

    //返回char[]
    final char[] getValue() {
        return value;
    }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张小帅和刘美美

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值