java 中 Stringbuff append源代码浅析

java

 public synchronized StringBuffer append(String str) {
        super.append(str);
        return this;
    } // 同步方法

  public AbstractStringBuilder append(String str) {
        if (str == null) str = "null";
        int len = str.length();
        ensureCapacityInternal(count + len);  // 是否扩容数组,如果扩容,返回将原数据拷入进去的数组
        str.getChars(0, len, value, count);      // 将str拷贝进数组
        count += len;
        return this;
    }

  private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        if (minimumCapacity - value.length > 0) // 原数组中数据内容长度+ 新需要拷贝的字符串长度超过原数组长度需要扩容
            expandCapacity(minimumCapacity);
    }

 void expandCapacity(int minimumCapacity) {
        int newCapacity = value.length * 2 + 2;   // 扩容按照原数组长度的2 * len + 2 的比例
        if (newCapacity - minimumCapacity < 0)
            newCapacity = minimumCapacity;  // 在需要append的字符串很长的情况下会出现
        if (newCapacity < 0) { //  oom
            if (minimumCapacity < 0) // overflow
                throw new OutOfMemoryError();
            newCapacity = Integer.MAX_VALUE;
        }
        value = Arrays.copyOf(value, newCapacity);  // 将原数据拷贝进一个扩容后的数组返回
    }

参考源代码,自己在工程代码中简单实现了功能.

      byte[] bytes = new byte[16]; // StringBuff源代码默认初始化是16字节
        String str = "hellowewewehellowewewe";  //  
        bytes = Arrays.copyOf(bytes, 100); // 简单扩容, 省略了判断
        str.getBytes(0, str.length(), bytes, 0);
        
        System.out.println(bytes);
        
        for (int i = 0; i < 100; i++){
            System.out.println(bytes[i]);
        }

顺便提下String

String str = "test";

str = str + "abc"; 使用的是StringBuilder对象添加,

早上大概花了半个小时, 简单看了下,下回有时间再仔细研究

以上是 java 中 Stringbuff append源代码浅析 的全部内容, 来源链接: utcz.com/z/392555.html

回到顶部