gpt4 book ai didi

java - StringBuilder容量()

转载 作者:太空狗 更新时间:2023-10-29 22:50:47 24 4
gpt4 key购买 nike

我注意到 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/

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