首页 > 其他 > 详细

StringBuffer扩容

时间:2020-05-13 23:40:39      阅读:63      评论:0      收藏:0      [点我收藏+]

1:默认初始长度 16

public StringBuffer() {
super(16);
}

2:append追加

    @Override
    public synchronized StringBuffer append(String str) {
        toStringCache = null;
        super.append(str);
        return this;
    }
    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;
    }
    private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        if (minimumCapacity - value.length > 0) {
            value = Arrays.copyOf(value,
                    newCapacity(minimumCapacity));
        }
    }

每次长度补够时,都会调用Arrays.copy() ,在此之前,还要计算新的char[]长度   newCapacity(minimumCapacity)

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

新的长度=最小长度*2+2  (最小长度:追加字符串后需要占用的长度)

 

 

 

 

StringBuffer扩容

原文:https://www.cnblogs.com/draymond/p/12885367.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!