Java8_131 rt包源码阅读记录

java.lang.StringBuilder、StringBu

2019-12-08  本文已影响0人  Oliver_Li

1. 描述:

2. 构造函数(StringBuilder)

//以入参”AAAA“为例
public StringBuilder(String str) {
    //初始数组长度就是4 + 16
    super(str.length() + 16);
    //调用AbstractStringBuilder的append(str),StringBuilder和StringBuffer的父类
    append(str);
}

public AbstractStringBuilder append(String str) {
    if (str == null)
        //数组当前后添加{'n','u','l','l'}
        return appendNull();
    int len = str.length();
    //扩容
    ensureCapacityInternal(count + len);
    //利用System.arraycopy()把str补到后面
    str.getChars(0, len, value, count);
    //记录已有元素个数
    count += len;
    return this;
}

//计算扩容长度,用Arrays.copyOf()设置value[]
private void ensureCapacityInternal(int minimumCapacity) {
      if (minimumCapacity - value.length > 0) {
          value = Arrays.copyOf(value,
                  newCapacity(minimumCapacity));
      }
  }

//计算扩容后长度。minCapacity是期望长度
private int newCapacity(int minCapacity) {
    // 2*minCapacity + 2
    int newCapacity = (value.length << 1) + 2;
    //如果还不够大直接等于minCapacity
    if (newCapacity - minCapacity < 0) {
        newCapacity = minCapacity;
    }
    //边界判定最大不超过Integer.MAX_VALUE,return
    return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
        ? hugeCapacity(minCapacity)
        : newCapacity;
}

3. append()(StringBuilder)

4. insert()(StringBuilder)

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

5. StringBuilder和StringBuffer

//-- StringBuilder.java --
public String toString() {
    return new String(value, 0, count);
}

//-- StringBuffer.java --
private transient char[] toStringCache;
public synchronized String toString() {
    if (toStringCache == null) {
        toStringCache = Arrays.copyOfRange(value, 0, count);
    }
    return new String(toStringCache, true);
}
上一篇下一篇

猜你喜欢

热点阅读