Java源码阅读 - AbstarctStringBuilder

  1. 基础类定义及属性
	 // 实现appendable需实现方法append,StringBuilder与StringBuffer常用方法
	abstract class AbstractStringBuilder implements Appendable, CharSequence

    // 字符数组
    char[] value;
 
    // 实际存的字符个数
    int count;
 
    // 无参构造方法
    AbstractStringBuilder() {
    }
 
    // 初始化数组大小的构造方法
    AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }
    // 返回count
    public int length() {
        return count;
    }
    // 当前数组的长度
    public int capacity() {
        return value.length;
    }
  1. 扩容方法
   // 扩容逻辑,当前容量先*2+2看是否足够,如果不够直接使用需要的容量扩容,需要的容量不可以大于最大容量MAX_ARRAY_SIZE
   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;
   }
	// 判断是否大于最大数组容量
   private int hugeCapacity(int minCapacity) {
       if (Integer.MAX_VALUE - minCapacity < 0) { // overflow
           throw new OutOfMemoryError();
       }
       return (minCapacity > MAX_ARRAY_SIZE)
           ? minCapacity : MAX_ARRAY_SIZE;
   }

   private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
   @Native public static final int MAX_VALUE = 0x7fffffff;

// 去除未使用容量
public void trimToSize() {
       if (count < value.length) {
           value = Arrays.copyOf(value, count);
       }
   }

// 判断长度是否足够,不够先扩容
public AbstractStringBuilder append(String str) {
       if (str == null)
           return appendNull();
       int len = str.length();
       ensureCapacityInternal(count + len);
       str.getChars(0, len, value, count);
       count += len;
       return this;
   }
  1. append布尔型及null
// 拼接true,false
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;
    }
// 拼接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;
    }

// 删除字符串方法
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;
    }

替换字符串,主要使用系统方法system.arraycopy

// 替换字符串方法
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;
   }
   
// system.arraycopy 方法,指定源对象和目的对象,分别设定复制开始点,分别复制在拼接
public static native void arraycopy(Object src,  int  srcPos,
                                   Object dest, int destPos,
                                   int length);
  1. 反转字符串

public AbstractStringBuilder reverse() {
        boolean hasSurrogates = false;
        int n = count - 1;
        for (int j = (n-1) >> 1; j >= 0; j--) {  // 计算(n-1)/2 定位中位数
            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;
    }
 
    /** 增补字符由于有2位字符,需要进行单独反转 */
    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;
                }
            }
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值