余腾

导航

Java源码分析八(AbstractStringBuilder)

Java源码分析八(AbstractStringBuilder)

分析一下StringBuilder 和StringBuffer的父类AbstractStringBuilder

基础的接口

Appendable(提供append方法),CharSequence(所有字符类型的父类)

属性分析

    //存储数据的字符串
    char[] value;
    //count是目前字符串中有几个数据 着重强调一下length()方法返回的不是value.length而是count  
    int count;
    //限制char 字符串的最大长度
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

构造器

    //提供空参构造器 这个无参数构造函数对于子类的序列化是必要的
AbstractStringBuilder() {
    }
    //给数组长度初始化 
 AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }
    //传入一个AbstractStringBuilder对象 然后判断count+len是否超过当前字符串的长度
  AbstractStringBuilder append(AbstractStringBuilder asb) {
        if (asb == null)
            return appendNull();
        int len = asb.length();
        //先判断长度够不够 如果不够 就创建一个新的数组长度为(value.length+asb.length)<<1+2 然后将原数据放进去
        ensureCapacityInternal(count + len);
        //value从count位置复制asb从0到len位置上的数据
        asb.getChars(0, len, value, count);
        //字符串增加了len个字符
        count += len;
        return this;
    }
    //将判断是否需要扩容后将String换成对应的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;
    }
    //在尾部增加一个字符
   public AbstractStringBuilder append(char c) {
        ensureCapacityInternal(count + 1);
        value[count++] = c;
        return this;
    }
    //增加数组 用到的原理System.arrayCopy方法 
    public AbstractStringBuilder append(char[] str) {
        int len = str.length;
        //判断字符串容量是否够大
        ensureCapacityInternal(count + len);
        //将str的字符从0开始到len位置 加到value count起始的位置
        System.arraycopy(str, 0, value, count, len);
        count += len;
        return this;
    }  
      //将double添加到字符串 如果是12.00就将12.0加入如果是12.11就加入12.11 12.01是 12.01
   public AbstractStringBuilder append(double d) {
        FloatingDecimal.appendTo(d,this);
        return this;
    }
      //float 放入到字符串 同理上面 后面第二位如果是0就直接省略了 12.005f是12.005
public AbstractStringBuilder append(float f) {
        FloatingDecimal.appendTo(f,this);
        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;
    }
    //与int 类似
  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;
    }
    //如果你要追加一个Person 如果没有重写toString方法就是 类位置反射名+2+hashCode值
  public AbstractStringBuilder append(Object obj) {
        return append(String.valueOf(obj));
    }
    //这个很神奇你如果传入的str是空的话 他会在最后填入"NULL"而不是不添加
  public AbstractStringBuilder append(String str) {
        if (str == null)
            return appendNull();
        int len = str.length();
        ensureCapacityInternal(count + len);
        //从str的0位置到len位置上元素 复制给value count开始后加入
        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);
        sb.getChars(0, len, value, count);
        count += len;
        return this;
    }
      //追加一个int值  判断是否是ASCII的代码点 如果是就追加一位 如果不是就去判断是否是有效代码点如果是就两位
public AbstractStringBuilder appendCodePoint(int codePoint) {
        final int count = this.count;

        if (Character.isBmpCodePoint(codePoint)) {
            ensureCapacityInternal(count + 1);
            value[count] = (char) codePoint;
            this.count = count + 1;
        } else if (Character.isValidCodePoint(codePoint)) {
            ensureCapacityInternal(count + 2);
            Character.toSurrogates(codePoint, value, count);
            this.count = count + 2;
        } else {
            throw new IllegalArgumentException();
        }
        return this;
    }
      //很特殊 如果传入的String默认是null 就调用此方法 在最后加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;
    }
    //返回当前字符串的长度 我们平时是length()方法是返回 但是他重写了 lenght返回的是count
    //即当前插入了多少数据
   public int capacity() {
        return value.length;
    }
      //根据索引位置返回对应的元素ASCII表中对应的位置
  public char charAt(int index) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        return value[index];
    }
      //返回指定位置前一个位置的point值
public int codePointBefore(int index) {
        int i = index - 1;
        if ((i < 0) || (i >= count)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return Character.codePointBeforeImpl(value, index, 0);
    }
    //返回从begin到end 位置的所有元素ASCII的总和值 (目前不知道什么时候用)
  public int codePointCount(int beginIndex, int endIndex) {
        if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) {
            throw new IndexOutOfBoundsException();
        }
        return Character.codePointCountImpl(value, beginIndex, endIndex-beginIndex);
    }
    //从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) {
          //将value 字符串从 value 从end开始后的数据复制到 value 的start后的数据(即覆盖)长度为count-end(end后的数据前移到start后)
            System.arraycopy(value, start+len, value, start, count-end);
            count -= len;
        }
        return this;
    }
      //删除制定位置的元素 原理 隔过去指定位置 将index+1开始的数据复制到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;
    }
    //判断是否需要
  public void ensureCapacity(int minimumCapacity) {
        if (minimumCapacity > 0)
            ensureCapacityInternal(minimumCapacity);
    }
    //扩容原理 创建一个新的cahr数组长度是(原数组长度)左移一位+2
   private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        if (minimumCapacity - value.length > 0) {
            value = Arrays.copyOf(value,
                    newCapacity(minimumCapacity));
        }
    }
      //将本字符串的value值从srcBegin 到srcEnd 传到dst数组dstBegin后的位置长度为srcEnd-srcBegin
    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);
    }
  //不多说
 final char[] getValue() {
        return value;
    }
      //扩容机制 先不考虑下面的不够的问题 默认是原数组的二倍+2如果还是不够就将你需要的空间 付过去就行
private int newCapacity(int minCapacity) {
        // overflow-conscious code
        int newCapacity = (value.length << 1) + 2;
        if (newCapacity - minCapacity < 0) {
            newCapacity = minCapacity;
        }
        return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
            ? hugeCapacity(minCapacity)
            : newCapacity;
    }
 
       //数组长度的临界问题(左移的时候越了int最大值的界)
    private int hugeCapacity(int minCapacity) {
        if (Integer.MAX_VALUE - minCapacity < 0) { // overflow
            throw new OutOfMemoryError();
        }
        return (minCapacity > MAX_ARRAY_SIZE)
            ? minCapacity : MAX_ARRAY_SIZE;
    }
    //寻找字符串中出现str第一次的下标
    public int indexOf(String str) {
        return indexOf(str, 0);
    }
      //寻找value中 以formIndex开始首次出现str的下标位置
     public int indexOf(String str, int fromIndex) {
        return String.indexOf(value, 0, count, str, fromIndex);
    }
    //插入问题 这里将其转换成了  对应位置 将booean值转换成了String 等一会说他的重载方法
   public AbstractStringBuilder insert(int offset, boolean b) {
        return insert(offset, String.valueOf(b));
    }
    //在offset位置 添加一个字符c 先判断是否数组还有空间 如果没有就扩容  添加原理和将offset后的元素往后移一位
    //将offset位置变为c
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;
    }
    //下面的原理大改都很类似不说了 很简单 
    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);
        System.arraycopy(str, 0, value, offset, len);
        count += len;
        return this;
    }
    //解释一下各个参数对应的含义 index  你想插入的位置  str 想插入的字符串 offset想插入字符串的元素位置
    //len 想要插入的长度  比如str=“123456” offset ——>2 len ——>3 就是插入345
   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);
        ensureCapacityInternal(count + len);
        System.arraycopy(value, index, value, index + len, count - index);
        System.arraycopy(str, offset, value, index, len);
        count += len;
        return this;
    }
    //等下数欧塔调用的这两个方法
  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());
    }
    //传入一个CharSequence 
 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);
        System.arraycopy(value, dstOffset, value, dstOffset + len,
                         count - dstOffset);
        //CharSequence 这个是String的父类没法调用这个方法 所以需要手段插入所以跟String不一样原理一样很简单
        for (int i=start; i<end; i++)
            value[dstOffset++] = s.charAt(i);
        count += len;
        return this;
    }
    //不多说
 public AbstractStringBuilder insert(int offset, double d) {
        return insert(offset, String.valueOf(d));
    }
    public AbstractStringBuilder insert(int offset, float f) {
        return insert(offset, String.valueOf(f));
    }
    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));
    }
    //将Object类转换成String  强调一下哦 如果没有改写toString 就是类名的反射地址+@+hashCode值
   public AbstractStringBuilder insert(int offset, Object obj) {
        return insert(offset, String.valueOf(obj));
    }
 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);
        //先offset后右移str.lenght个单位
        System.arraycopy(value, offset, value, offset + len, count - offset);
        //将str的值从offset赋给value 
        str.getChars(value, offset);
        count += len;
        return this;
    }
    //str最后一次出现的位置默认从最后一位count开始找
 public int lastIndexOf(String str) {
        return lastIndexOf(str, count);
    }
    //从formIndex开始往前找最后一次出现的位置 
    public int lastIndexOf(String str, int fromIndex) {
        return String.lastIndexOf(value, 0, count, str, fromIndex);
    }
    // 超级强调哦 这个lengh()是字符串数组中插入到多少个元素了 和value.lenght没关系哦 重点强调
   public int length() {
        return count;
    }
      //返回此 String 中从给定的 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);
    }
    //将str到end位置替换成str很简单自己看看
  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;
    }
    //数组的反转很简单 0和count换 1和--count换就行 换到中点就结束   
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;
    }
    //reverse的辅助方法
  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;
                }
            }
        }
    }
    //将index位置的元素改成你输入的新字符
 public void setCharAt(int index, char ch) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        value[index] = ch;
    }
     //设置count的值 如果newLength大于count之前为空的位置给他用\0给他安排上即ASCII中的0即终止含义的0
 public void setLength(int newLength) {
        if (newLength < 0)
            throw new StringIndexOutOfBoundsException(newLength);
        ensureCapacityInternal(newLength);

        if (count < newLength) {
            Arrays.fill(value, count, newLength, '\0');
        }

        count = newLength;
    }
      //subString 全家桶
   public CharSequence subSequence(int start, int end) {
        return substring(start, end);
    }
    public String substring(int start) {
        return substring(start, count);
    }
    //意思是返回一个String 值是value的从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);
    }
    //抽象方法需要重写到时候他的子类StringBuilder和StringBuffer会重写
 public abstract String toString();
    //调整value的长度大小 为了节省空间 现在谁还用 内存都大的离谱 意思就是现在value是满的
    //到count了 如果count后面你加了数据 直接没了 不过我们遍历的时候也是从0 到count  后面的也不会遍历
   public void trimToSize() {
        if (count < value.length) {
            value = Arrays.copyOf(value, count);
        }
    }

posted on 2021-09-14 11:17  余腾  阅读(42)  评论(0编辑  收藏  举报

Fork me on Gitee