StringBuffer 中append方法底層實現


/*
* StringBuffer中append()不用創建對象可以連接字符串,想知道是如何完成的。
*/

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) { //若小於等於零,說明str為空字符串,不做修改 value = Arrays.copyOf(value, newCapacity(minimumCapacity)); } } public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) { //srcBegin 為起始位置0;srcEnd:src的長度 dst[]為復制后的數組value ;
//dstBegin 原有value的長度,也就是原有count接下來的位置  
if (srcBegin < 0) { throw new StringIndexOutOfBoundsException(srcBegin); } if (srcEnd > value.length) { throw new StringIndexOutOfBoundsException(srcEnd); } if (srcBegin > srcEnd) { throw new StringIndexOutOfBoundsException(srcEnd - srcBegin); } System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin); 
 } public static native void arraycopy(Object src,  int srcPos, Object dest, int destPos, int length);                          //調用其他語言編寫的代碼和代碼庫,完成復制
 src - 源數組。
 srcPos - 源數組中的起始位置。dest - 目標數組
                                                                      destPos - 目標數據中的起始位置。length - 要復制的數組元素的數量
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM