首先出現的是與你的問題一個問題:
String s = "orange";
s.append("apple");
這裏的兩個對象被創建
正確,創建了兩個對象,字符串「橙色」和字符串「蘋果「,在StringBuffer/StringBuilder內部,如果我們不溢出緩衝區,則不會創建對象。所以這些代碼行創建2或3個對象。
StringBuilder s = new StringBuilder("Orange");
s.append("apple");
現在,這裏只有一個對象被創建
我不知道你在哪裏得到的是,在這裏你創建一個StringBuilder對象,一個「橙色」字符串,一個「蘋果」字符串,總共有3個對象,如果我們溢出了StringBuilder緩衝區,則爲4。 (我將數組創建爲對象創建)。
我看了你的問題,StringBuilder的怎麼辦追加而不創建新的對象(如果緩衝區不溢出)?
你應該看看StringBuilder
,因爲它是非線程安全的實現。代碼很有趣,很容易閱讀。我添加了內嵌評論。
作爲內部結構有一個char數組,而不是一個字符串。它最初建造的長度爲16,每次超過容量時都會增加。如果要在char數組中添加字符串,則不需要創建新的對象。
StringBuilder
延伸AbstractStringBuilder
,在那裏你會發現下面的代碼:
/**
* The value is used for character storage.
*/
char value[];
由於並非所有的陣列將在給定時間使用,另外一個重要的變量是長度:
/**
* The count is the number of characters used.
*/
int count;
追加有很多超載,但最有趣的是以下幾種:
public AbstractStringBuilder append(String str) {
if (str == null) str = "null"; //will literally append "null" in case of null
int len = str.length(); //get the string length
if (len == 0) return this; //if it's zero, I'm done
int newCount = count + len; //tentative new length
if (newCount > value.length) //would the new length fit?
expandCapacity(newCount); //oops, no, resize my array
str.getChars(0, len, value, count); //now it will fit, copy the chars
count = newCount; //update the count
return this; //return a reference to myself to allow chaining
}
String.getChars(int srcBegin,int srcEnd,char [] dst,int dstBegin)將此字符串中的字符複製到目標字符數組中。
所以,追加方法相當簡單,這隻神奇的左邊發現是expandCapacity
,那就是:
void expandCapacity(int minimumCapacity) {
//get the current length add one and double it
int newCapacity = (value.length + 1) * 2;
if (newCapacity < 0) { //if we had an integer overflow
newCapacity = Integer.MAX_VALUE; //just use the max positive integer
} else if (minimumCapacity > newCapacity) { //is it enough?
//if doubling wasn't enough, use the actual length computed
newCapacity = minimumCapacity;
}
//copy the old value in the new array
value = Arrays.copyOf(value, newCapacity);
}
Arrays.copyOf(的char []原來,INT newLength)複製指定的數組,截斷或填充空字符(如有必要),以便副本具有指定的長度。
在我們的例子中,填充,因爲我們正在擴大長度。
中有問題的幾個假設這是不正確的。 'new StringBuilder()'和'new String()'創建兩個對象。 –
是我的問題嗎? ;) –