本文最后更新于:2020年11月12日 下午

StringBuilder类探究

简介

  • 实现自AbstractStringBuilder
  • 主要方法未synchronize修饰,线程不安全
  • 单线程内适用
  • final类,不可继承
  • 内容可变(内部字符数组未用final)

Tips

  • 性能 StringBuilder > StringBuffer > String (添加大量字符时)
  • 单一线程优先使用

源码分析

  • AbstractStringBuilder

    abstract class AbstractStringBuilder implements Appendable, CharSequence {
        //字符数组    
        char[] value;
    
        //已用长度
        int count;
        
        //数据初始化方法   
        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) {
            // overflow-conscious code
            if (minimumCapacity - value.length > 0) {
                value = Arrays.copyOf(value,
                        newCapacity(minimumCapacity));
            }
        }
    
        //数组长度最大值
        private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    
        //重新设置长度
        private int newCapacity(int minCapacity) {
            //2倍+2扩容
            int newCapacity = (value.length << 1) + 2;
            //此处取较大值(默认的2倍+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();
            }
            //最大也不能超过Integer.MaxValue(最大值)
            return (minCapacity > MAX_ARRAY_SIZE)
                ? minCapacity : MAX_ARRAY_SIZE;
        }
    
        //去除未使用空间,实际是对已用数组的拷贝
        public void trimToSize() {
            if (count < value.length) {
                value = Arrays.copyOf(value, count);
            }
        }
    
        //重新设置长度
        public void setLength(int newLength) {
            if (newLength < 0)
                throw new StringIndexOutOfBoundsException(newLength);
            //确保空间足够
            ensureCapacityInternal(newLength);
    
            if (count < newLength) {
                //不足部分'\0'填充    
                Arrays.fill(value, count, newLength, '\0');
            }
            
            count = newLength;
        }
    
        //获取给定下标的字符
        @Override
        public char charAt(int index) {
            if ((index < 0) || (index >= count))
                throw new StringIndexOutOfBoundsException(index);
            return value[index];
        }
    
        //获取给定下标的码值(一般为ASCII码)
        public int codePointAt(int index) {
            if ((index < 0) || (index >= count)) {
                throw new StringIndexOutOfBoundsException(index);
            }
            return Character.codePointAtImpl(value, index, count);
        }
    
        public int codePointBefore(int index) {
            int i = index - 1;
            if ((i < 0) || (i >= count)) {
                throw new StringIndexOutOfBoundsException(index);
            }
            return Character.codePointBeforeImpl(value, index, 0);
        }
        
        public int codePointCount(int beginIndex, int endIndex) {
            if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) {
                throw new IndexOutOfBoundsException();
            }
            return Character.codePointCountImpl(value, beginIndex, endIndex-beginIndex);
        }
    
        public int offsetByCodePoints(int index, int codePointOffset) {
            if (index < 0 || index > count) {
                throw new IndexOutOfBoundsException();
            }
            return Character.offsetByCodePointsImpl(value, 0, count,
                                                    index, codePointOffset);
        }
        
        //数组拷贝,将原数组的起始位置坐标 存入指定数组的指定位置
        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);
        }
        
        //设置给定下标的字符
        public void setCharAt(int index, char ch) {
            if ((index < 0) || (index >= count))
                throw new StringIndexOutOfBoundsException(index);
            value[index] = ch;
        }
    
        //尾部添加字符串
        public AbstractStringBuilder append(Object obj) {
            return append(String.valueOf(obj));
        }
        
        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;
        }
    
        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;
        }
    
        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;
        }
    
        @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());
        }
        
        //添加空串
        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[j] = s.charAt(i);
            count += len;
            return this;
        }
    
        //添加字符串
        public AbstractStringBuilder append(char[] str) {
            int len = str.length;
            ensureCapacityInternal(count + len);
            //此处使用System.arraycopy
            System.arraycopy(str, 0, value, count, len);
            count += len;
            return this;
        }
    
      
        public AbstractStringBuilder append(char str[], int offset, int len) {
            if (len > 0)                // let arraycopy report AIOOBE for len < 0
                ensureCapacityInternal(count + len);
            System.arraycopy(str, offset, value, count, len);
            count += len;
            return this;
        }
    
        //添加布尔值
        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;
        }
    
        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 append(float f) {
            FloatingDecimal.appendTo(f,this);
            return this;
        }
    
        public AbstractStringBuilder append(double d) {
            FloatingDecimal.appendTo(d,this);
            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;
        }
    
       
        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;
        }
    
        //删除指定位置字符
        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);
            //原来end字符串进行拷贝,空出位置
            System.arraycopy(value, end, value, start + len, count - end);
            //str存入
            str.getChars(value, start);
            count = newCount;
            return this;
        }
        
        //字符切割
        public String substring(int start) {
            return substring(start, count);
        }
      
        @Override
        public CharSequence subSequence(int start, int end) {
            return substring(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);
        }
    
        //插入数据
        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);
            //str字符串插入
            System.arraycopy(str, offset, value, index, len);
            count += len;
            return this;
        }
    
        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);
            System.arraycopy(value, offset, value, offset + len, count - offset);
            str.getChars(value, offset);
            count += len;
            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;
        }
    
        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;
            ensureCapacityInternal(count + len);
            System.arraycopy(value, dstOffset, value, dstOffset + len,
                             count - dstOffset);
            for (int i=start; i<end; i++)
                value[dstOffset++] = s.charAt(i);
            count += len;
            return this;
        }
    
        
        public AbstractStringBuilder insert(int offset, boolean b) {
            return insert(offset, String.valueOf(b));
        }
    
        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, 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));
        }
    
        //获取Str首次出现的下标
        public int indexOf(String str) {
            return indexOf(str, 0);
        }
    
        public int indexOf(String str, int fromIndex) {
            return String.indexOf(value, 0, count, str, fromIndex);
        }
        
        //最后一次出现的下标
        public int lastIndexOf(String str) {
            return lastIndexOf(str, count);
        }
    
        public int lastIndexOf(String str, int fromIndex) {
            return String.lastIndexOf(value, 0, count, str, fromIndex);
        }
    
        //字符串翻转
        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;
        }
    
        /** Outlined helper method for 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;
                    }
                }
            }
        }
    
        @Override
        public abstract String toString();
    
        /**
         * Needed by {@code String} for the contentEquals method.
         */
        final char[] getValue() {
            return value;
        }
    
    }
  • StringBuilder类

    public final class StringBuilder
        extends AbstractStringBuilder
        implements java.io.Serializable, CharSequence
    {
    
       
        static final long serialVersionUID = 4383685877147921099L;
    
        //初始字符数组大小为16    
        public StringBuilder() {
            super(16);
        }
    
        public StringBuilder(int capacity) {
            super(capacity);
        }
    
        //根据字符串初始化
        public StringBuilder(String str) {
            //长度为 16+字符串长度
            super(str.length() + 16);
            append(str);
        }
    
        public StringBuilder(CharSequence seq) {
            this(seq.length() + 16);
            append(seq);
        }
    
        @Override
        public StringBuilder append(Object obj) {
            return append(String.valueOf(obj));
        }
    
        @Override
        public StringBuilder append(String str) {
            super.append(str);
            return this;
        }
    
        public StringBuilder append(StringBuffer sb) {
            super.append(sb);
            return this;
        }
    
        @Override
        public StringBuilder append(CharSequence s) {
            super.append(s);
            return this;
        }
    
        /**
         * @throws     IndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder append(CharSequence s, int start, int end) {
            super.append(s, start, end);
            return this;
        }
    
        @Override
        public StringBuilder append(char[] str) {
            super.append(str);
            return this;
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder append(char[] str, int offset, int len) {
            super.append(str, offset, len);
            return this;
        }
    
        @Override
        public StringBuilder append(boolean b) {
            super.append(b);
            return this;
        }
    
        @Override
        public StringBuilder append(char c) {
            super.append(c);
            return this;
        }
    
        @Override
        public StringBuilder append(int i) {
            super.append(i);
            return this;
        }
    
        @Override
        public StringBuilder append(long lng) {
            super.append(lng);
            return this;
        }
    
        @Override
        public StringBuilder append(float f) {
            super.append(f);
            return this;
        }
    
        @Override
        public StringBuilder append(double d) {
            super.append(d);
            return this;
        }
    
        /**
         * @since 1.5
         */
        @Override
        public StringBuilder appendCodePoint(int codePoint) {
            super.appendCodePoint(codePoint);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder delete(int start, int end) {
            super.delete(start, end);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder deleteCharAt(int index) {
            super.deleteCharAt(index);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder replace(int start, int end, String str) {
            super.replace(start, end, str);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder insert(int index, char[] str, int offset,
                                    int len)
        {
            super.insert(index, str, offset, len);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder insert(int offset, Object obj) {
                super.insert(offset, obj);
                return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder insert(int offset, String str) {
            super.insert(offset, str);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder insert(int offset, char[] str) {
            super.insert(offset, str);
            return this;
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder insert(int dstOffset, CharSequence s) {
                super.insert(dstOffset, s);
                return this;
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder insert(int dstOffset, CharSequence s,
                                    int start, int end)
        {
            super.insert(dstOffset, s, start, end);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder insert(int offset, boolean b) {
            super.insert(offset, b);
            return this;
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder insert(int offset, char c) {
            super.insert(offset, c);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder insert(int offset, int i) {
            super.insert(offset, i);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder insert(int offset, long l) {
            super.insert(offset, l);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder insert(int offset, float f) {
            super.insert(offset, f);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuilder insert(int offset, double d) {
            super.insert(offset, d);
            return this;
        }
    
        @Override
        public int indexOf(String str) {
            return super.indexOf(str);
        }
    
        @Override
        public int indexOf(String str, int fromIndex) {
            return super.indexOf(str, fromIndex);
        }
    
        @Override
        public int lastIndexOf(String str) {
            return super.lastIndexOf(str);
        }
    
        @Override
        public int lastIndexOf(String str, int fromIndex) {
            return super.lastIndexOf(str, fromIndex);
        }
    
        @Override
        public StringBuilder reverse() {
            super.reverse();
            return this;
        }
    
        @Override
        public String toString() {
            // Create a copy, don't share the array
            return new String(value, 0, count);
        }
    
        //流处理相关
        private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
            s.defaultWriteObject();
            s.writeInt(count);
            s.writeObject(value);
        }
    
        /**
         * readObject is called to restore the state of the StringBuffer from
         * a stream.
         */
        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            count = s.readInt();
            value = (char[]) s.readObject();
        }
    
    }

本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!

ArrayList探究 上一篇
StringBuffer类探究 下一篇

 目录