作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
根据 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/
根据 oracle 文档,请参阅此链接 here public void ensureCapacity(int minimumCapacity) Ensures that the capacity i
我是一名优秀的程序员,十分优秀!