StringBuffer.append() 的未知行为

Unknown behaviour of StringBuffer.append()

StringBuffer.append() 的怪异行为: javatpoint 状态:

If the number of the character increases from its current capacity, it > increases the capacity by (oldcapacity*2)+2.

可以通过以下代码演示:

class test {
        public static void main(String[] args) {
                StringBuffer sb = new StringBuffer();

                sb.append("abcdef"); // 16;
                System.out.println(sb.capacity());

                sb.append("1234561711"); // 34
                System.out.println(sb.capacity()); // 34
        }
}

但是,它在以下代码中表现出奇怪的行为:

class test {
        public static void main(String[] args) {
                StringBuffer sb = new StringBuffer();

                sb.append("abcdef"); // 16;
                System.out.println(sb.capacity());

                sb.append("12345617111111111111111111111111111111"); // 44 total 44 character in sb, so capacity should be 70 as it goes from 16, 34, 70, 142 etc.
                System.out.println(sb.capacity()); // 34
        }
}

如果我们使用两个追加上述字符的容量将是70! 所以,我认为只有一个限制打破了一个 append()

StringBufferensureCapacity 的逻辑在 Javadoc 中说明:

void java.lang.AbstractStringBuilder.ensureCapacity(int minimumCapacity)

Ensures that the capacity is at least equal to the specified minimum.If the current capacity is less than the argument, then a new internal array is allocated with greater capacity. The new capacity is the larger of:

• The minimumCapacity argument.

• Twice the old capacity, plus 2.

在您的第二个代码段中,44(这是所需的最小容量,因为在第二个 append 之后 StringBuffer 中将有 44 个字符)大于旧容量的两倍,加上2(即 34)。因此新容量为 44.