首先出现的是与你的问题一个问题:
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()'创建两个对象。 –
是我的问题吗? ;) –