java - StringBuilder容量()

标签 java stringbuilder capacity

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

相关文章:

java - 计算所有价格项目的总和

java - 将 stringbuffer 转换为字符串并按字母顺序排列单词

c# - 方法返回不同的字符串第二次调用 - 参数相同

c# - 从使用 stringbuilder 构建的字符串中删除最后一个字符的最佳方法

java - 检查 Hashtable 是否完整 java

java - 无法将 XMLTYPE 数据类型从 Oracle 加载到 Spark SQL

Java无法确定应用程序类

java - 在 Android 中发送单选按钮值

asp.net - 如何测试我的 ASP.NET 网站是否每天都托管在共享服务器上以供大量访问者访问?

cocoa - NSMutableArray initWithCapacity 的细微差别