StringBuilder容量()

发布于 2024-09-08 04:16:57 字数 129 浏览 2 评论 0原文

我注意到 capacity 方法返回 StringBuilder 容量,没有逻辑 方式...有时它的值等于字符串长度,有时它更大...

是否有一个方程式可以知道它的逻辑是什么?

I noticed that the capacity method returns StringBuilder capacity without a logic
way ... sometime its value is equals to the string length other time it's greater...

is there an equation for know which is its logic?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

云归处 2024-09-15 04:16:57

我将尝试用一些例子来解释这一点。

public class StringBuilderDemo {
     public static void main(String[] args) {
         StringBuilder sb = new StringBuilder();
         System.out.println(sb.length());
         System.out.println(sb.capacity());
     }
}

length() - 构建器中字符序列的长度
由于此字符串生成器不包含任何内容,因此其长度将为 0。

capacity() - 已分配的字符空间数。
当您尝试构造具有空内容的字符串构建器时,默认情况下它会将初始化大小设置为长度+16,即0+16。因此这里的容量将返回 16。

注意:capacity() 方法返回的容量始终大于或等于长度(通常大于),并且会根据需要自动扩展以适应字符串生成器的添加。

容量函数背后的逻辑:

  1. 如果您没有使用任何内容初始化stringbuilder,则默认容量将被视为16个字符的容量。
  2. 如果使用任何内容初始化 stringbuilder,则容量将为内容长度+16。
  3. 当您向 stringbuilder 对象添加新内容时,如果当前容量不足以容纳新值,则它将增长(先前数组容量+1)*2。

此分析取自 实际的 StringBuilder.java 代码

I will try to explain this with some example.

public class StringBuilderDemo {
     public static void main(String[] args) {
         StringBuilder sb = new StringBuilder();
         System.out.println(sb.length());
         System.out.println(sb.capacity());
     }
}

length() - the length of the character sequence in the builder
since this stringbuilder doesn't contain any content, its length will be 0.

capacity() - the number of character spaces that have been allocated.
When you try to construct a stringbuilder with empty content, by default it takes the initialize size as length+16 which is 0+16. so capacity would return 16 here.

Note: The capacity, which is returned by the capacity() method, is always greater than or equal to the length (usually greater than) and will automatically expand as necessary to accommodate additions to the string builder.

The logic behind the capacity function:

  1. If you don't initialize stringbuilder with any content, default capacity will be taken as 16 characters capacity.
  2. If you initialize stringbuilder with any content, then capacity will be content length+16.
  3. When you add new content to stringbuilder object, if current capacity is not sufficient to take new value, then it will grow by (previous array capacity+1)*2.

This analysis is take from actual StringBuilder.java code

帥小哥 2024-09-15 04:16:57

当您追加到 StringBuilder 时,会发生以下逻辑:

if (newCount > value.length) {
    expandCapacity(newCount);
}

其中 newCount 是所需的字符数,value.length 是当前大小缓冲区。

expandCapacity 只是增加支持 char[] 的大小

ensureCapacity() 方法是调用 expandCapacity()< /code>,其文档说:

确保容量至少等于指定的最小值。如果当前容量小于参数,则分配一个具有更大容量的新内部数组。新容量是以下值中的较大者:

  • minimumCapacity 参数。
  • 旧容量的两倍,再加上 2。

如果minimumCapacity参数为非正数,则此方法不执行任何操作并简单地返回。

When you append to the StringBuilder, the following logic happens:

if (newCount > value.length) {
    expandCapacity(newCount);
}

where newCount is the number of characters needed, and value.length is the current size of the buffer.

expandCapacity simply increases the size of the backing char[]

The ensureCapacity() method is the public way to call expandCapacity(), and its docs say:

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.

归途 2024-09-15 04:16:57

此函数执行的操作与您的预期不同 - 它为您提供了此 StringBuilder 实例内存此时可以容纳的最大字符数。

字符串生成器必读

This function does something different than you expect - it gives you the max number of chars this StringBuilder instance memory can hold at this time.

String Builder must read

仅一夜美梦 2024-09-15 04:16:57

逻辑如下:
如果您定义一个没有构造函数的 StringBuilder 类的新实例,例如 new StringBuilder();,则默认容量为 16。
构造函数可以是 intString
对于 String 构造函数,默认容量的计算方式如下

int newCapacity = string.length() + 16;

对于 int 构造函数,容量的计算方式如下

int newCapacity = intSpecified + 16;

如果附加一个新的 StringStringBuilder并且String的新长度大于当前容量,则容量计算如下:

int newCapacity = (oldCapacity + 1) * 2;

Here's the logic:
If you define a new instance of the StringBuilder class without a constructor, like so new StringBuilder(); the default capacity is 16.
A constructor can be either an int or a String.
For a String constructor, the default capacity is calculated like this

int newCapacity = string.length() + 16;

For an int constructor, the capacity is calculated like this

int newCapacity = intSpecified + 16;

If a new String is appended to the StringBuilder and the new length of the String is greater than the current capacity, then the capacity is calculated like this:

int newCapacity = (oldCapacity + 1) * 2;
万劫不复 2024-09-15 04:16:57

编辑:抱歉 - 以下是有关 .NET StringBuilder 的信息,与原始问题并不严格相关。

http://johnnycoder.com/blog/2009/01 /05/stringbuilder-required-capacity-algorithm/

StringBuilder 为您可能添加到其中的子字符串分配空间(很像 List 为其包装的数组创建空间)。如果您想要字符串的实际长度,请使用 StringBuilder.Length。

EDIT: Apologies - the below is information on .NET's StringBuilder, and is not strictly relevant to the original question.

http://johnnycoder.com/blog/2009/01/05/stringbuilder-required-capacity-algorithm/

StringBuilder allocates space for substrings you might add to it (much like List creates space the array it wraps). If you want the actual length of the string, use StringBuilder.Length.

逆流 2024-09-15 04:16:57

从API:

每个字符串生成器都有一个容量。
只要字符的长度
字符串中包含的序列
建造者不超过能力,
没有必要分配一个新的
内部缓冲区。如果内部
缓冲区溢出,它是自动的
变大了。

每当您追加内容时,都会进行检查以确保更新的 StringBuilder 不会超出其容量,如果超出,则会调整 StringBuilder 的内部存储大小:

int len = str.length();
int newCount = count + len;
if (newCount > value.length)
  expandCapacity(newCount);

当添加的数据超过其容量时,它将重新调整- 根据以下公式确定大小:

void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
    if (newCapacity < 0) {
        newCapacity = Integer.MAX_VALUE;
    } else if (minimumCapacity > newCapacity) {
    newCapacity = minimumCapacity;
}
    value = Arrays.copyOf(value, newCapacity);
}

有关详细信息,请参阅 JDK 附带的 src.zip 文件。 (以上摘自 1.6 JDK 的片段)

From the API:

Every string builder has a capacity.
As long as the length of the character
sequence contained in the string
builder does not exceed the capacity,
it is not necessary to allocate a new
internal buffer. If the internal
buffer overflows, it is automatically
made larger.

Whenever you append something, there is a check to make sure that the updated StringBuilder won't exceed its capacity, and if it does, the internal storage of the StringBuilder is resized:

int len = str.length();
int newCount = count + len;
if (newCount > value.length)
  expandCapacity(newCount);

When data is added to it that exceeds its capacity it is re-sized according to the following formula:

void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
    if (newCapacity < 0) {
        newCapacity = Integer.MAX_VALUE;
    } else if (minimumCapacity > newCapacity) {
    newCapacity = minimumCapacity;
}
    value = Arrays.copyOf(value, newCapacity);
}

See the src.zip file that comes with the JDK for more information. (Above snippets taken from the 1.6 JDK)

旧伤还要旧人安 2024-09-15 04:16:57

你可以进入JDK代码看看它是如何工作的,它基于一个char数组:new char[capacity],它类似于ArrayList的工作原理( 何时使用 LinkedList 而不是 ArrayList?)。两者都使用数组来提高“硬件效率”,技巧是分配一大块内存并在其中工作,直到内存耗尽并需要下一个大块来继续(扩展/增长)。

You can go inside the JDK code and see how it works, it is based on a char array: new char[capacity], it is similar to how the ArrayList works (When to use LinkedList over ArrayList?). Both use arrays to be 'hardware efficient', the trick is to allocate a large chunk of memory and work in it until you run out of memory and need the next big chunk to continue (expand/grow).

最舍不得你 2024-09-15 04:16:57

以 Java 1.8

public AbstractStringBuilder append(String str) {
    if (str == null)
        return appendNull();
    int len = str.length();
    ensureCapacityInternal(count + len);
    str.getChars(0, len, value, count);
    count += len;
    return this;
}

private void ensureCapacityInternal(int minimumCapacity) {
    // overflow-conscious code
    if (minimumCapacity - value.length > 0) {
        value = Arrays.copyOf(value,
                newCapacity(minimumCapacity));
    }
}

为例:

StringBuilder str = new StringBuilder();  
System.out.println(str.capacity()); //16

str.append("123456789012345"); 
System.out.println(str.capacity()); //16

str.append("12345678901234567890"); 
System.out.println(str.capacity()); // 15 + 20 = 35

in Java 1.8

public AbstractStringBuilder append(String str) {
    if (str == null)
        return appendNull();
    int len = str.length();
    ensureCapacityInternal(count + len);
    str.getChars(0, len, value, count);
    count += len;
    return this;
}

private void ensureCapacityInternal(int minimumCapacity) {
    // overflow-conscious code
    if (minimumCapacity - value.length > 0) {
        value = Arrays.copyOf(value,
                newCapacity(minimumCapacity));
    }
}

for example :

StringBuilder str = new StringBuilder();  
System.out.println(str.capacity()); //16

str.append("123456789012345"); 
System.out.println(str.capacity()); //16

str.append("12345678901234567890"); 
System.out.println(str.capacity()); // 15 + 20 = 35
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文