StringBuffer 如何在不创建两个对象的情况下实现追加函数?

2022-09-01 13:42:32

这是一个面试问题。我被要求实现追加函数。面试后我看到了代码。但是我无法理解如何通过创建单个对象来完成操作。StringBuffer

我是这样想的。

String s = "orange";
s.append("apple");

这里创建了两个对象。

StringBuilder s = new StringBuilder("Orange");
s.append("apple");

现在这里只创建了一个对象。

Java是如何执行此操作的?


答案 1

首先,您的问题有问题:

String s = "orange";
s.append("apple");

这里创建了两个对象

正确,创建了两个对象,字符串“橙色”和字符串“苹果”,在StringBuffer/StringBuilder中,如果我们不溢出缓冲区,则不会创建任何对象。因此,这些代码行会创建 2 或 3 个对象。

StringBuilder s = new StringBuilder("Orange");
s.append("apple");

现在这里只创建了一个对象

我不知道你从哪里得到的,在这里你创建一个StringBuilder对象,一个“橙色”字符串,一个“苹果”字符串,总共3个对象,或者如果我们溢出StringBuilder缓冲区,则创建4个。(我将数组创建计为对象创建)。


我读了你的问题,StringBuilder如何在不创建新对象的情况下进行追加(当缓冲区未溢出时)?

您应该查看 ,因为它是非线程安全实现。代码很有趣,易于阅读。我添加了内联注释。StringBuilder

作为内部结构,有一个字符数组,而不是一个字符串。它最初建造的长度为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) 将此字符串中的字符复制到目标字符数组中。

所以,append方法很简单,唯一需要发现的魔力就是,这里是: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[] original, int newLength) 复制指定的数组,用空字符截断或填充(如有必要),以便副本具有指定的长度。

在我们的例子中,填充,因为我们正在扩展长度。


答案 2

源头是你的朋友,卢克!

这是 AbstractStringBuilder 的源代码