gpt4 book ai didi

java - StringBuffer 类中的 EnsureCapacity(intminimumCapacity) 方法

转载 作者:行者123 更新时间:2023-12-01 22:39:33 26 4
gpt4 key购买 nike

根据 oracle 文档,请参阅此链接 here

public void 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.
If the minimumCapacity argument is nonpositive, this method takes no action and simply returns.

我正在尝试使用代码示例清除它:

    StringBuffer buff1 = new StringBuffer("tuts point");
System.out.println("buffer1 = " + buff1); // lenght = 10

// returns the current capacity of the string buffer 1
System.out.println("Old Capacity = " + buff1.capacity()); // capacity = 16+10=26 characters
/*
* increases the capacity, as needed, to the specified amount in the
* given string buffer object
*/
// returns twice the capacity plus 2
buff1.ensureCapacity(30);
System.out.println("New Capacity = " + buff1.capacity()); // 26*2 + 2 = 54

如果ensureCapacity方法中的minimumCapacity参数在27 - 53之间,那么我确实得到了预期的答案(返回两倍的容量加上2)。但是,如果参数>=55,则容量仅等于该参数。

    // does not return (twice the capacity plus 2)
buff1.ensureCapacity(55);
System.out.println("New Capacity = " + buff1.capacity()); // 55

为什么这里的答案是 55?

最佳答案

这是由于对 AbstractStringBuilder 类的调用造成的:

void expandCapacity(int minimumCapacity) {
int newCapacity = value.length * 2 + 2;
if (newCapacity - minimumCapacity < 0)
newCapacity = minimumCapacity;
if (newCapacity < 0) {
if (minimumCapacity < 0) // overflow
throw new OutOfMemoryError();
newCapacity = Integer.MAX_VALUE;
}
value = Arrays.copyOf(value, newCapacity);
}

因此,当它增加容量时,它会将容量至少增加 (2 * 原始容量) + 2,达到提供的值,以较大者为准。

如果容量为 26,而您传递了 30:

(26 * 2) + 2 = 54,这超过了 30,因此新容量将为 54。

如果容量为 26,而您传递了 55:

(26 * 2) + 2 = 54,这小于 55,因此新容量将为 55。

关于java - StringBuffer 类中的 EnsureCapacity(intminimumCapacity) 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26404043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com