您的位置:首頁 >國內 >

append方法是用來做什么的_append方法

2023-06-22 06:25:34 來源:互聯網

1、Java中的append( )方法其實是創建了一個新的數組,擴大了長度,將需要添加的字符串給復制到這個新的數組中。

2、JAVA中Stringbuffer有append( )方法:而Stringbuffer是動態字符串數組,append( )是往動態字符串數組添加,跟“xxxx”+“yyyy”相當‘+’號。


(資料圖片)

3、跟String不同的是Stringbuffer是放一起的,String1+String2和***.append("yyyy")雖然打印效果一樣,但在內存中表示卻不一樣、String1+String2 存在于不同的兩個地址內存,***.append(Stringbuffer2)放再一起。

4、StringBuffer是線程安全的,多用于多線程。

5、擴展資料查看StringBuffer的append()方法如圖所示代碼:[emailprotected] synchronized StringBuffer append(String str) {toStringCache = null;***.append(str);return this;}其中toStringCache是Cleared whenever the StringBuffer is modified.2、進入AbstractStringBuilder的append()方法public AbstractStringBuilder append(String str) {if (str == null)return appendNull();int len = ***.length();ensureCapacityInternal(count + len);***.getchars(0, len, value, count);count += len;return this;}如果參數str為空返回appendNull(); 該方法最終返回return this.3、進入ensureCapacityInternal()方法private void ensureCapacityInternal(int minimumCapacity) {// overflow-conscious codeif (minimumCapacity - ***.length > 0) {value = ***.copyof(value,newCapacity(minimumCapacity));}}copyOf(char[] original, int newLength)的方法查JDK幫助文檔可知:復制指定的數組,復制具有指定的長度。

6、4、進入String的getChars()方法public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {//0,len=5,value=[hello],count=5if (srcBegin < 0) {throw new StringIndexOutOfBoundsException(srcBegin);}if (srcEnd > ***.length) {throw new StringIndexOutOfBoundsException(srcEnd);}if (srcBegin > srcEnd) {throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);}***.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);}5、最終調用的是***.arraycopy的方法:public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)/*src - 源數組。

7、srcPos - 源數組中的起始位置。

8、dest - 目標數組。

9、destPos - 目的地數據中的起始位置。

10、length - 要復制的數組元素的數量。

11、*/***.arraycopy([world], 0, [hello], 5, 5);將指定源數組中的數組從指定位置復制到目標數組的指定位置。

12、參考資料:百度百科-append。

本文分享完畢,希望對你有所幫助。

關鍵詞: