您好,現在軟糖來為大家解答以上的問題。append方法和appendto方法的區別,append方法相信很多小伙伴還不知道,現在讓我們一起來看看吧!
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()方法如圖所示代碼:進入append方法@Overridepublic 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)***.arraycopy([world], 0, [hello], 5, 5);將指定源數組中的數組從指定位置復制到目標數組的指定位置。
12、參考資料:百度百科-append。
本文就為大家分享到這里,希望小伙伴們會喜歡。