zoukankan      html  css  js  c++  java
  • StringBuffer扩容

    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  (最小长度:追加字符串后需要占用的长度)

     

  • 相关阅读:
    洛谷P2875 [USACO07FEB]牛的词汇The Cow Lexicon
    poj2241 The Tower of Babylon
    2015 Noip提高组 Day2
    2015 Noip提高组 Day1
    poj3252 Round Numbers
    hdu4734 F(x)
    hdu2089 不要62
    洛谷P1831 杠杆数
    洛谷P2113 看球泡妹子
    洛谷P3110 [USACO14DEC]驮运Piggy Back
  • 原文地址:https://www.cnblogs.com/draymond/p/12885367.html
Copyright © 2011-2022 走看看