Java-AbstractStringBuilder

声明

1)该文章整理自网上的大牛和专家无私奉献的资料,具体引用的资料请看参考文献。
2)本文仅供学术交流,非商用。如果某部分不小心侵犯了大家的利益,还望海涵,并联系博主删除。
3)博主才疏学浅,文中如有不当之处,请各位指出,共同进步,谢谢。
4)此属于第一版本,若有错误,还需继续修正与增删。还望大家多多指点。大家都共享一点点,一起为祖国科研的推进添砖加瓦。

前言

这个抽象类是StringBuilder和StringBuffer的直接父类,而且定义了很多方法,因此在学习这两个类之间建议先学习 AbstractStringBuilder抽象类
该类在源码中注释是以JDK1.5开始作为前两个类的父类存在的,可是直到JDK1.8的API中,关于StringBuilder和StringBuffer的父类还是Object

类声明

abstract class AbstractStringBuilder implements Appendable, CharSequence 
类声明实现了两个接口,其中CharSequence这个字符序列的接口已经很熟悉了:
该接口规定了需要实现该字符序列的长度:length();
可以取得下标为index的的字符:charAt(int index);
可以得到该字符序列的一个子字符序列: subSequence(int start, int end);
规定了该字符序列的String版本(重写了父类Object的toString()):toString();

Appendable接口顾名思义,定义添加的’规则’:
append(CharSequence csq) throws IOException:如何添加一个字符序列
append(CharSequence csq, int start, int end) throws IOException:如何添加一个字符序列的一部分
append(char c) throws IOException:如何添加一个字符

变量

    /**
     * The value is used for character storage.
     */
    char value[];

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

value为该字符序列的具体存储,count为实际存储的数量
注意:(和String中的value和count不同,String中的这两者都是不可变的(final修饰),并且不能对value[]直接操作;而AbstractStringBuilder的两者都是可变的,并且也定义了getValues方法让我们可以直接拿到value[],value实际上是个动态数组,和ArrayList的实现有很多相似的地方)

构造器

    /** 
     * This no-arg constructor is necessary for serialization of subclasses.
     */
     AbstractStringBuilder() {
    }

    /** 
     * Creates an AbstractStringBuilder of the specified capacity.
     */
    AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }

方法

序号是按照方法在源码中出现的顺序来的,所以不是连着的

1.length():返回已经存储的实际长度(就是count值)

public int length() {
    return count;
    }

2.capacity():这个单词是’容量’的意思,得到目前该value数组的实际大小

 public int capacity() {
    return value.length;
    }

3.ensureCapacity(int minimumCapacity):确保value数组的容量是否够用,如果不够用,调用expandCapacity(minimumCapacity)方法扩容,参数为需要的容量

 public void ensureCapacity(int minimumCapacity) {
    if (minimumCapacity > value.length) {
        expandCapacity(minimumCapacity);
    }
    }

4.expandCapacity(int minimumCapacity):对数组进行扩容,参数为需要的容量

 void expandCapacity(int minimumCapacity) {
    int newCapacity = (value.length + 1) * 2;
        if (newCapacity < 0) {
            newCapacity = Integer.MAX_VALUE;
        } else if (minimumCapacity > newCapacity) {
        newCapacity = minimumCapacity;
    }
        value = Arrays.copyOf(value, newCapacity);
    }

扩容的算法:
如果调用了该函数,说明容量不够用了,先将当前容量+1的二倍(newCapacity)与需要的容量(minimumCapacity)比较。
如果比需要的容量大,那就将容量扩大到容量+1的二倍;如果比需要的容量小,那就直接扩大到需要的容量。
使用Arrays.copyOf()这个非常熟悉的方法来使数组容量动态扩大

5.trimToSize():如果value数组的容量有多余的,那么就把多余的全部都释放掉

public void trimToSize() {
        if (count < value.length) {
            value = Arrays.copyOf(value, count);
        }
    }

6.setLength(int newLength):强制增大实际长度count的大小,容量如果不够就用 expandCapacity()扩大;将扩大的部分全部用’\0’(ASCII码中的null)来初始化

 public void setLength(int newLength) {
    if (newLength < 0)
        throw new StringIndexOutOfBoundsException(newLength);
    if (newLength > value.length)
        expandCapacity(newLength);

    if (count < newLength) {
        for (; count < newLength; count++)
        value[count] = '\0';
    } else {
            count = newLength;
        }
    }

7.charAt(int index):得到下标为index的字符

public char charAt(int index) {
    if ((index < 0) || (index >= count))
        throw new StringIndexOutOfBoundsException(index);
    return value[index];
    }

8.codePointAt(int index):得到代码点

public int codePointAt(int index) {
        if ((index < 0) || (index >= count)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return Character.codePointAt(value, index);
    }

9.getChars(int srcBegin, int srcEnd, char dst[],int dstBegin):将value[]的[srcBegin, srcEnd)拷贝到dst[]数组的desBegin开始处

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);
    }

10.substring(int start)/substring(int start, int end):得到子字符串

 public String substring(int start) {
        return substring(start, count);
    }

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);
    }

11.subSequence(int start, int end):得到一个子字符序列

public CharSequence subSequence(int start, int end) {
        return substring(start, end);
    }

12.reverse():将value给倒序存放(注意改变的就是本value,而不是创建了一个新的AbstractStringBuilder然后value为倒序)

public AbstractStringBuilder reverse() {
    boolean hasSurrogate = false;
    int n = count - 1;
    for (int j = (n-1) >> 1; j >= 0; --j) {
        char temp = value[j];
        char temp2 = value[n - j];
        if (!hasSurrogate) {
        hasSurrogate = (temp >= Character.MIN_SURROGATE && temp <= Character.MAX_SURROGATE)
            || (temp2 >= Character.MIN_SURROGATE && temp2 <= Character.MAX_SURROGATE);
        }
        value[j] = temp2;
        value[n - j] = temp;
    }
    if (hasSurrogate) {
        // Reverse back all valid surrogate pairs
        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;
            }
        }
        }
    }
    return this;
    }

toString():唯一的一个抽象方法:toString()

   public abstract String toString();

唯一的一个final方法:getValue(),得到value数组。可以对其直接操作

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

CRUD操作

一:改

13.setCharAt(int index, char ch):直接设置下标为index的字符为ch

 public void setCharAt(int index, char ch) {
    if ((index < 0) || (index >= count))
        throw new StringIndexOutOfBoundsException(index);
    value[index] = ch;
    }

14.replace(int start, int end, String str):用字符串str替换掉value[]数组的[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);
    if (newCount > value.length)
        expandCapacity(newCount);

        System.arraycopy(value, end, value, start + len, count - end);
        str.getChars(value, start);
        count = newCount;
        return this;
    }

增(AbstractStringBuilder类及其子类中最重要的操作;Appendable接口的具体实现)
其中append都表示’追加’,insert都表示’插入’:

15.append(Object obj):利用Object(或任何对象)的toString方法转成字符串然后添加到该value[]中

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

16.append()的核心代码:append(String str)/append(StringBuffer sb)/append(CharSequence s)。直接修改value[],并且’添加’的意思为链接到原value[]的实际count的后面

 public AbstractStringBuilder append(String str) {
    if (str == null) str = "null";
        int len = str.length();
    if (len == 0) return this;
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    str.getChars(0, len, value, count);
    count = newCount;
    return this;
    }

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

    // Documentation in subclasses because of synchro difference
    public AbstractStringBuilder append(CharSequence s) {
        if (s == null)
            s = "null";
        if (s instanceof String)
            return this.append((String)s);
        if (s instanceof StringBuffer)
            return this.append((StringBuffer)s);
        return this.append(s, 0, s.length());
    }

同时注意返回的都是AbstractStringBuilder,意味着append方法可以连续无限调用,即AbstractStringBuilder对象.append(参数1).append(参数2).append(参数三)…………;

17.append(CharSequence s, int start, int end):添加字符序列s的部分序列,范围是[start,end)

 public AbstractStringBuilder append(CharSequence s, int start, int end) {
        if (s == null)
            s = "null";
    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;
    if (len == 0)
            return this;
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
        for (int i=start; i<end; i++)
            value[count++] = s.charAt(i);
        count = newCount;
    return this;
    }

18.append(char str[]):添加一个字符数组

public AbstractStringBuilder append(char str[]) { 
    int newCount = count + str.length;
    if (newCount > value.length)
        expandCapacity(newCount);
        System.arraycopy(str, 0, value, count, str.length);
        count = newCount;
        return this;
    }

19.append(char str[], int offset, int len):添加一个字符数组的一部分,该部分的范围是[offset,offset+len);

public AbstractStringBuilder append(char str[], int offset, int len) {
        int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    System.arraycopy(str, offset, value, count, len);
    count = newCount;
    return this;
    }

20.append(boolean b):添加布尔值。

public AbstractStringBuilder append(boolean b) {
        if (b) {
            int newCount = count + 4;
            if (newCount > value.length)
                expandCapacity(newCount);
            value[count++] = 't';
            value[count++] = 'r';
            value[count++] = 'u';
            value[count++] = 'e';
        } else {
            int newCount = count + 5;
            if (newCount > value.length)
                expandCapacity(newCount);
            value[count++] = 'f';
            value[count++] = 'a';
            value[count++] = 'l';
            value[count++] = 's';
            value[count++] = 'e';
        }
    return this;
    }

21.append(char c):添加一个字符

public AbstractStringBuilder append(char c) {
        int newCount = count + 1;
    if (newCount > value.length)
        expandCapacity(newCount);
    value[count++] = c;
    return this;
    }

22.append(int i):添加一个整数

public AbstractStringBuilder append(int i) {
        if (i == Integer.MIN_VALUE) {
            append("-2147483648");
            return this;
        }
        int appendedLength = (i < 0) ? stringSizeOfInt(-i) + 1 
                                     : stringSizeOfInt(i);          //stringSizeOfInt方法在下面,得到参数整数的位数。
        int spaceNeeded = count + appendedLength;
        if (spaceNeeded > value.length)
            expandCapacity(spaceNeeded);
    Integer.getChars(i, spaceNeeded, value);
        count = spaceNeeded;
        return this;
    }

 final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
                                     99999999, 999999999, Integer.MAX_VALUE };


    static int stringSizeOfInt(int x) {
        for (int i=0; ; i++)
            if (x <= sizeTable[i])
                return i+1;
    }

23.append(long l):添加一个长整型的数据,原理同上一个append

public AbstractStringBuilder append(long l) {
        if (l == Long.MIN_VALUE) {
            append("-9223372036854775808");
            return this;
        }
        int appendedLength = (l < 0) ? stringSizeOfLong(-l) + 1 
                                     : stringSizeOfLong(l);
        int spaceNeeded = count + appendedLength;
        if (spaceNeeded > value.length)
            expandCapacity(spaceNeeded);
    Long.getChars(l, spaceNeeded, value);
        count = spaceNeeded;
        return this;
    }

    // Requires positive x
    static int stringSizeOfLong(long x) {
        long p = 10;
        for (int i=1; i<19; i++) {
            if (x < p)
                return i;
            p = 10*p;
        }
        return 19;
    }

24.append(float f)/append(double d):添加一个浮点数。

 public AbstractStringBuilder append(float f) {
    new FloatingDecimal(f).appendTo(this);
    return this;
    }

 public AbstractStringBuilder append(double d) {
    new FloatingDecimal(d).appendTo(this);
    return this;
    }

以上是append

二:增
25.insert(int index, char str[], int offset,int len):(insert的核心代码)在value[]的下标为index位置插入数组str的一部分,该部分的范围为:[offset,offset+len);

 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);
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    System.arraycopy(value, index, value, index + len, count - index);
    System.arraycopy(str, offset, value, index, len);
    count = newCount;
    return this;
    }

26.insert(int offset, Object obj):在value[]的offset位置插入Object(或者说所有对象)的String版。

public AbstractStringBuilder insert(int offset, Object obj) {
    return insert(offset, String.valueOf(obj));
    }

27.insert(int offset, String str):在value[]的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();
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    System.arraycopy(value, offset, value, offset + len, count - offset);
    str.getChars(value, offset);
    count = newCount;
    return this;
    }

28.insert(int offset, char str[]):在value[]的offset位置插入字符数组

public AbstractStringBuilder insert(int offset, char str[]) {
    if ((offset < 0) || (offset > length()))
        throw new StringIndexOutOfBoundsException(offset);
    int len = str.length;
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    System.arraycopy(value, offset, value, offset + len, count - offset);
    System.arraycopy(str, 0, value, offset, len);
    count = newCount;
    return this;
    }

29.insert(int dstOffset, CharSequence s)/insert(int dstOffset, CharSequence s,int start, int end):插入字符序列

public AbstractStringBuilder insert(int dstOffset, CharSequence s) {
        if (s == null)
            s = "null";
        if (s instanceof String)
            return this.insert(dstOffset, (String)s);
        return this.insert(dstOffset, s, 0, s.length());
    }

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;
        if (len == 0)
            return this;
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    System.arraycopy(value, dstOffset, value, dstOffset + len,
                         count - dstOffset);
    for (int i=start; i<end; i++)
            value[dstOffset++] = s.charAt(i);
    count = newCount;
        return this;
    }

30.插入基本类型:除了char是直接插入外,其他都是先转成String,然后调用编号为28的insert方法

public AbstractStringBuilder insert(int offset, boolean b) {
    return insert(offset, String.valueOf(b));
    }


    public AbstractStringBuilder insert(int offset, char c) {
    int newCount = count + 1;
    if (newCount > value.length)
        expandCapacity(newCount);
    System.arraycopy(value, offset, value, offset + 1, count - offset);
    value[offset] = c;
    count = newCount;
    return this;
    }
    
    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));
    }

三:删
31.delete(int start, int end):删掉value数组的[start,end)部分,并将end后面的数据移到start位置

 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;
    }

32.deleteCharAt(int index):删除下标为index的数据,并将后面的数据前移一位

 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;
    }

四:查(其实CRUD前面那几个方法中有一两个也算查找):
33.indexOf(String str):在value[]中找字符串str,若能找到,返回第一个字符串的第一个字符的下标

 public int indexOf(String str) {
    return indexOf(str, 0);
    }

34.从fromIndex开始,在value[]中找字符串str,若能找到,返回第一个字符串的第一个字符的下标

public int indexOf(String str, int fromIndex) {
        return String.indexOf(value, 0, count,
                              str.toCharArray(), 0, str.length(), fromIndex);
    }

35.lastIndexOf(String str):从后往前找

public int lastIndexOf(String str) {
        return lastIndexOf(str, count);
    }

36.lastIndexOf(String str, int fromIndex):从后往前到fromIndex,找子串str

 public int lastIndexOf(String str, int fromIndex) {
        return String.lastIndexOf(value, 0, count,
                              str.toCharArray(), 0, str.length(), fromIndex);
    }

总结

这个类没什么特别的, 但还是稍微总结一下

  1. 构造器里立即初始化数组
  2. 扩容方式为 扩容前长度 * 2 + 2
  3. 当前第2条说的不严谨. 首先想想为什么扩容呢? 因为插入一个字符串的时候, 剩余空间不足了, 所以扩容. 如果插入的这个字符串太长, 导致扩容一次也无法容纳下呢? 那么就直接把长度设置为 扩容前长度+ 插入的字符串长度 .
  4. 大规模使用了System.arraycopy方法.
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值