我注意到 capacity
方法在没有逻辑的情况下返回 StringBuilder
capacity
方式...有时它的值等于字符串长度其他时间它更大...
是否有一个等式可以知道它的逻辑是什么?
最佳答案
当您附加到 StringBuilder
时,会发生以下逻辑:
if (newCount > value.length) {
expandCapacity(newCount);
}
其中 newCount
是所需的字符数,value.length
是缓冲区的当前大小。
expandCapacity
只是增加后备 char[]
ensureCapacity()
方法是调用 expandCapacity()
的公共(public)方法,它的文档说:
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.
关于java - StringBuilder容量(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3184244/