Java StringBuilder 容量()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3184244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
StringBuilder capacity()
提问by xdevel2000
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...
我注意到该capacity
方法StringBuilder
没有逻辑方式返回容量......有时它的值等于字符串长度其他时候它更大......
is there an equation for know which is its logic?
是否有一个方程式可以知道它的逻辑是什么?
回答by InsertNickHere
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.
此函数执行的操作与您预期的不同 - 它为您提供此 StringBuilder 实例内存此时可以容纳的最大字符数。
回答by Alex Humphrey
EDIT: Apologies - the below is information on .NET's StringBuilder, and is not strictly relevant to the original question.
编辑:道歉 - 以下是关于 .NET 的 StringBuilder 的信息,与原始问题并不严格相关。
http://johnnycoder.com/blog/2009/01/05/stringbuilder-required-capacity-algorithm/
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.
StringBuilder 为您可能添加的子字符串分配空间(很像 List 为它包装的数组创建空间)。如果您想要字符串的实际长度,请使用 StringBuilder.Length。
回答by Bozho
When you append to the StringBuilder
, the following logic happens:
当您附加到 时StringBuilder
,会发生以下逻辑:
if (newCount > value.length) {
expandCapacity(newCount);
}
where newCount
is the number of characters needed, and value.length
is the current size of the buffer.
其中newCount
是所需的字符数,value.length
是缓冲区的当前大小。
expandCapacity
simply increases the size of the backing char[]
expandCapacity
只是增加了背衬的大小 char[]
The ensureCapacity()
method is the public way to call expandCapacity()
, and its docs say:
该ensureCapacity()
方法是调用 的公共方式expandCapacity()
,其文档说:
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.
确保容量至少等于指定的最小值。如果当前容量小于参数,则分配一个具有更大容量的新内部数组。新容量为以下较大者:
- minimumCapacity 参数。
- 旧容量的两倍,再加上 2。
如果 minimumCapacity 参数为非正数,则此方法不执行任何操作并仅返回。
回答by Catchwa
From the API:
从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:
每当您追加内容时,都会进行检查以确保更新后的 StringBuilder 不会超过其容量,如果超过,则调整 StringBuilder 的内部存储大小:
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)
有关src.zip
详细信息,请参阅JDK 附带的文件。(以上摘自 1.6 JDK 的片段)
回答by user1923551
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.
length()
- 生成器中字符序列的长度,因为此字符串生成器不包含任何内容,因此其长度将为 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.
capacity()
- 已分配的字符空间数。当你尝试构造一个空内容的 stringbuilder 时,默认情况下它的初始化大小为 length+16,即 0+16。所以这里的容量将返回 16。
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.
注意:由 capacity() 方法返回的容量始终大于或等于长度(通常大于),并将根据需要自动扩展以适应字符串生成器的添加。
The logic behind the capacity function:
容量函数背后的逻辑:
- If you don't initialize stringbuilder with any content, default capacity will be taken as 16 characters capacity.
- If you initialize stringbuilder with any content, then capacity will be content length+16.
- 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.
- 如果您不使用任何内容初始化 stringbuilder,则默认容量将被视为 16 个字符的容量。
- 如果您使用任何内容初始化 stringbuilder,则容量将为内容长度+16。
- 当您向 stringbuilder 对象添加新内容时,如果当前容量不足以获取新值,则它将增长(以前的数组容量+1)*2。
This analysis is take from actual StringBuilder.java code
回答by Christophe Roussy
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).
您可以进入 JDK 代码并查看它是如何工作的,它基于一个字符数组:new char[capacity]
,它的ArrayList
工作原理类似于(何时使用 LinkedList over ArrayList?)。两者都使用数组来实现“硬件高效”,诀窍是分配一大块内存并在其中工作,直到内存用完并需要下一个大块继续(扩展/增长)。
回答by Ayokunle Paul
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
这是逻辑:如果你定义一个StringBuilder
没有构造函数的类的新实例,new StringBuilder();
默认容量是 16。构造函数可以是 anint
或 a String
。对于String
构造函数,默认容量是这样计算的
int newCapacity = string.length() + 16;
For an int
constructor, the capacity is calculated like this
对于int
构造函数,容量是这样计算的
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:
如果将新String
附加到StringBuilder
并且 的新长度String
大于当前容量,则容量计算如下:
int newCapacity = (oldCapacity + 1) * 2;
回答by HenryChuang
in Java 1.8
在 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