本文最后更新于:2020年11月9日 早上

StringBuffer类探究

简介

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

Tips

源码分析

  • 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;
        }
    
        /**
         * Ensures that the capacity is at least equal to the specified minimum.
         * If the current capacity is less than the argument, then a new internal
         * array is allocated with greater capacity. The new capacity is the
         * larger of:
         * <ul>
         * <li>The {@code minimumCapacity} argument.
         * <li>Twice the old capacity, plus {@code 2}.
         * </ul>
         * If the {@code minimumCapacity} argument is nonpositive, this
         * method takes no action and simply returns.
         * Note that subsequent operations on this object can reduce the
         * actual capacity below that requested here.
         *
         * @param   minimumCapacity   the minimum desired capacity.
         */
        public void ensureCapacity(int minimumCapacity) {
            if (minimumCapacity > 0)
                ensureCapacityInternal(minimumCapacity);
        }
    
        //内部字符数组扩容
        private void ensureCapacityInternal(int minimumCapacity) {
            //给定数组大于当前数组最大长度时,进行扩容 
            if (minimumCapacity - value.length > 0) {
                value = Arrays.copyOf(value,
                        newCapacity(minimumCapacity));
            }
        }
    
        //内部数组最大长度,防止 outOfMemoryException
        private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    
        //根据给定最小值,获取数组大小并返回
        private int newCapacity(int minCapacity) {
            // overflow-conscious code,2倍加2
            int newCapacity = (value.length << 1) + 2;
            //此处选择较大的值进行赋值
            if (newCapacity - minCapacity < 0) {
                newCapacity = minCapacity;
            }
            //过小或者过大进行hugeCapacity,否则使用给定值
            return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
                ? hugeCapacity(minCapacity)
                : newCapacity;
        }
        //处理上述极值情况
        private int hugeCapacity(int minCapacity) {
            //超过Integer最大值则抛出异常
            if (Integer.MAX_VALUE - minCapacity < 0) { // overflow
                throw new OutOfMemoryError();
            }
            //选取较大的一个值返回
            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;
        }
    
        //返回给定下标的值(char类型)
        @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);
            //char数组复制
            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;
        }
    
        //尾部添加AbstractStringBuilder串
        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(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;
        }
        
        //添加int数值
        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);
    
            System.arraycopy(value, end, value, start + len, count - end);
            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);
            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);
            //offset开始字符插入 value的len长度之后
            System.arraycopy(value, offset, value, offset + len, count - offset);
            //空出空间存放str
            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);
        }
    
        //调用Str数组的方法
        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;
        }
        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;
        }
    
    }
  • StringBuffer类
        
     public final class StringBuffer
        extends AbstractStringBuilder
        implements java.io.Serializable, CharSequence
    {
    
        //缓存数组,当值变动时修改
        private transient char[] toStringCache;
        
        static final long serialVersionUID = 3388685877147921107L;
    
        //初始化,默认大小16
        public StringBuffer() {
            super(16);
        }
        
        public StringBuffer(int capacity) {
            super(capacity);
        }
    
        //带值初始化时,大小为16+串长度
        public StringBuffer(String str) {
            super(str.length() + 16);
            append(str);
        }
    
        public StringBuffer(CharSequence seq) {
            this(seq.length() + 16);
            append(seq);
        }
        
        //同步方法,获取长度
        @Override
        public synchronized int length() {
            return count;
        }
        
        //同步方法,获取容量
        @Override
        public synchronized int capacity() {
            return value.length;
        }
    
    
        @Override
        public synchronized void ensureCapacity(int minimumCapacity) {
            super.ensureCapacity(minimumCapacity);
        }
    
        /**
         * @since      1.5
         */
        @Override
        public synchronized void trimToSize() {
            super.trimToSize();
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         * @see        #length()
         */
        @Override
        public synchronized void setLength(int newLength) {
            toStringCache = null;
            super.setLength(newLength);
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         * @see        #length()
         */
        @Override
        public synchronized char charAt(int index) {
            if ((index < 0) || (index >= count))
                throw new StringIndexOutOfBoundsException(index);
            return value[index];
        }
    
        /**
         * @since      1.5
         */
        @Override
        public synchronized int codePointAt(int index) {
            return super.codePointAt(index);
        }
    
        /**
         * @since     1.5
         */
        @Override
        public synchronized int codePointBefore(int index) {
            return super.codePointBefore(index);
        }
    
        /**
         * @since     1.5
         */
        @Override
        public synchronized int codePointCount(int beginIndex, int endIndex) {
            return super.codePointCount(beginIndex, endIndex);
        }
    
        /**
         * @since     1.5
         */
        @Override
        public synchronized int offsetByCodePoints(int index, int codePointOffset) {
            return super.offsetByCodePoints(index, codePointOffset);
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public synchronized void getChars(int srcBegin, int srcEnd, char[] dst,
                                          int dstBegin)
        {
            super.getChars(srcBegin, srcEnd, dst, dstBegin);
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         * @see        #length()
         */
        @Override
        public synchronized void setCharAt(int index, char ch) {
            if ((index < 0) || (index >= count))
                throw new StringIndexOutOfBoundsException(index);
            toStringCache = null;
            value[index] = ch;
        }
    
        @Override
        public synchronized StringBuffer append(Object obj) {
            toStringCache = null;
            super.append(String.valueOf(obj));
            return this;
        }
    
        @Override
        public synchronized StringBuffer append(String str) {
            toStringCache = null;
            super.append(str);
            return this;
        }
    
      
        public synchronized StringBuffer append(StringBuffer sb) {
            toStringCache = null;
            super.append(sb);
            return this;
        }
    
        /**
         * @since 1.8
         */
        @Override
        synchronized StringBuffer append(AbstractStringBuilder asb) {
            toStringCache = null;
            super.append(asb);
            return this;
        }
    
        /**
         * Appends the specified {@code CharSequence} to this
         * sequence.
         * <p>
         * The characters of the {@code CharSequence} argument are appended,
         * in order, increasing the length of this sequence by the length of the
         * argument.
         *
         * <p>The result of this method is exactly the same as if it were an
         * invocation of this.append(s, 0, s.length());
         *
         * <p>This method synchronizes on {@code this}, the destination
         * object, but does not synchronize on the source ({@code s}).
         *
         * <p>If {@code s} is {@code null}, then the four characters
         * {@code "null"} are appended.
         *
         * @param   s the {@code CharSequence} to append.
         * @return  a reference to this object.
         * @since 1.5
         */
        @Override
        public synchronized StringBuffer append(CharSequence s) {
            toStringCache = null;
            super.append(s);
            return this;
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         * @since      1.5
         */
        @Override
        public synchronized StringBuffer append(CharSequence s, int start, int end)
        {
            toStringCache = null;
            super.append(s, start, end);
            return this;
        }
    
        @Override
        public synchronized StringBuffer append(char[] str) {
            toStringCache = null;
            super.append(str);
            return this;
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public synchronized StringBuffer append(char[] str, int offset, int len) {
            toStringCache = null;
            super.append(str, offset, len);
            return this;
        }
    
        @Override
        public synchronized StringBuffer append(boolean b) {
            toStringCache = null;
            super.append(b);
            return this;
        }
    
        @Override
        public synchronized StringBuffer append(char c) {
            toStringCache = null;
            super.append(c);
            return this;
        }
    
        @Override
        public synchronized StringBuffer append(int i) {
            toStringCache = null;
            super.append(i);
            return this;
        }
    
        /**
         * @since 1.5
         */
        @Override
        public synchronized StringBuffer appendCodePoint(int codePoint) {
            toStringCache = null;
            super.appendCodePoint(codePoint);
            return this;
        }
    
        @Override
        public synchronized StringBuffer append(long lng) {
            toStringCache = null;
            super.append(lng);
            return this;
        }
    
        @Override
        public synchronized StringBuffer append(float f) {
            toStringCache = null;
            super.append(f);
            return this;
        }
    
        @Override
        public synchronized StringBuffer append(double d) {
            toStringCache = null;
            super.append(d);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         * @since      1.2
         */
        @Override
        public synchronized StringBuffer delete(int start, int end) {
            toStringCache = null;
            super.delete(start, end);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         * @since      1.2
         */
        @Override
        public synchronized StringBuffer deleteCharAt(int index) {
            toStringCache = null;
            super.deleteCharAt(index);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         * @since      1.2
         */
        @Override
        public synchronized StringBuffer replace(int start, int end, String str) {
            toStringCache = null;
            super.replace(start, end, str);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         * @since      1.2
         */
        @Override
        public synchronized String substring(int start) {
            return substring(start, count);
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         * @since      1.4
         */
        @Override
        public synchronized CharSequence subSequence(int start, int end) {
            return super.substring(start, end);
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         * @since      1.2
         */
        @Override
        public synchronized String substring(int start, int end) {
            return super.substring(start, end);
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         * @since      1.2
         */
        @Override
        public synchronized StringBuffer insert(int index, char[] str, int offset,
                                                int len)
        {
            toStringCache = null;
            super.insert(index, str, offset, len);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public synchronized StringBuffer insert(int offset, Object obj) {
            toStringCache = null;
            super.insert(offset, String.valueOf(obj));
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public synchronized StringBuffer insert(int offset, String str) {
            toStringCache = null;
            super.insert(offset, str);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public synchronized StringBuffer insert(int offset, char[] str) {
            toStringCache = null;
            super.insert(offset, str);
            return this;
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         * @since      1.5
         */
        @Override
        public StringBuffer insert(int dstOffset, CharSequence s) {
            // Note, synchronization achieved via invocations of other StringBuffer methods
            // after narrowing of s to specific type
            // Ditto for toStringCache clearing
            super.insert(dstOffset, s);
            return this;
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         * @since      1.5
         */
        @Override
        public synchronized StringBuffer insert(int dstOffset, CharSequence s,
                int start, int end)
        {
            toStringCache = null;
            super.insert(dstOffset, s, start, end);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public  StringBuffer insert(int offset, boolean b) {
            // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
            // after conversion of b to String by super class method
            // Ditto for toStringCache clearing
            super.insert(offset, b);
            return this;
        }
    
        /**
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public synchronized StringBuffer insert(int offset, char c) {
            toStringCache = null;
            super.insert(offset, c);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuffer insert(int offset, int i) {
            // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
            // after conversion of i to String by super class method
            // Ditto for toStringCache clearing
            super.insert(offset, i);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuffer insert(int offset, long l) {
            // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
            // after conversion of l to String by super class method
            // Ditto for toStringCache clearing
            super.insert(offset, l);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuffer insert(int offset, float f) {
            // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
            // after conversion of f to String by super class method
            // Ditto for toStringCache clearing
            super.insert(offset, f);
            return this;
        }
    
        /**
         * @throws StringIndexOutOfBoundsException {@inheritDoc}
         */
        @Override
        public StringBuffer insert(int offset, double d) {
            // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
            // after conversion of d to String by super class method
            // Ditto for toStringCache clearing
            super.insert(offset, d);
            return this;
        }
    
        /**
         * @since      1.4
         */
        @Override
        public int indexOf(String str) {
            // Note, synchronization achieved via invocations of other StringBuffer methods
            return super.indexOf(str);
        }
    
        /**
         * @since      1.4
         */
        @Override
        public synchronized int indexOf(String str, int fromIndex) {
            return super.indexOf(str, fromIndex);
        }
    
        /**
         * @since      1.4
         */
        @Override
        public int lastIndexOf(String str) {
            // Note, synchronization achieved via invocations of other StringBuffer methods
            return lastIndexOf(str, count);
        }
    
        /**
         * @since      1.4
         */
        @Override
        public synchronized int lastIndexOf(String str, int fromIndex) {
            return super.lastIndexOf(str, fromIndex);
        }
    
        /**
         * @since   JDK1.0.2
         */
        @Override
        public synchronized StringBuffer reverse() {
            toStringCache = null;
            super.reverse();
            return this;
        }
    
        @Override
        public synchronized String toString() {
            if (toStringCache == null) {
                toStringCache = Arrays.copyOfRange(value, 0, count);
            }
            return new String(toStringCache, true);
        }
    
        //序列化相关方法
        private static final java.io.ObjectStreamField[] serialPersistentFields =
        {
            new java.io.ObjectStreamField("value", char[].class),
            new java.io.ObjectStreamField("count", Integer.TYPE),
            new java.io.ObjectStreamField("shared", Boolean.TYPE),
        };
    
       
        private synchronized void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
            java.io.ObjectOutputStream.PutField fields = s.putFields();
            fields.put("value", value);
            fields.put("count", count);
            fields.put("shared", false);
            s.writeFields();
        }
    
       
        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            java.io.ObjectInputStream.GetField fields = s.readFields();
            value = (char[])fields.get("value", null);
            count = fields.get("count", 0);
        }
    }

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

StringBuilder类探究 上一篇
String类探究 下一篇

 目录