java 中 Stringbuff append原始碼淺析

來源:互聯網
上載者:User

標籤:io   java   ar   for   資料   sp   on   代碼   c   

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

 

java 中 Stringbuff append原始碼淺析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.