源--StringBuilder


  • append的方法實現

/**初始化大小爲16*/
public StringBuilder() {
    super(16);
}

public StringBuilder(int capacity) {
    super(capacity);
}

public StringBuilder(String str) {
    super(str.length() + 16);
    append(str);
}

/**實現方式主要是通過不斷擴大char[]的容量,往char[]尾追加char*/
@Override
public StringBuilder append(String str) {
    super.append(str);
    return this;
}

/**StringBuilder父類AbstractStringBuilder方法*/
public AbstractStringBuilder append(String str) {
    if (str == null)
        return appendNull();
    int len = str.length();
    ensureCapacityInternal(count + len);
    //具體實現如何追加字符串str
    str.getChars(0, len, value, count);
    count += len;
    return this;
}

/**該方法是String類裏面的方法*/
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
    if (srcBegin < 0) {
        throw new StringIndexOutOfBoundsException(srcBegin);
    }
    if (srcEnd > value.length) {
        throw new StringIndexOutOfBoundsException(srcEnd);
    }
    if (srcBegin > srcEnd) {
        throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
    }
    //srcEnd-srcBegin:需要拷貝的長度,其中System.arraycopy方法屬於Native方法
    System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章