What is the capacity of a StringBuffer?

2019-01-26 06:36发布

When I run this code:

StringBuffer name = new StringBuffer("stackoverflow.com");
System.out.println("Length: " + name.length() + ", capacity: " + name.capacity());

it gives output:

Length: 17, capacity: 33

Obvious length is related to number of characters in string, but I am not sure what capacity is? Is that number of characters that StringBuffer can hold before reallocating space?

13条回答
趁早两清
2楼-- · 2019-01-26 06:59

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

From: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/StringBuffer.html

查看更多
劫难
3楼-- · 2019-01-26 07:02

Yes, you're correct, see the JavaDoc for more information:

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

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-26 07:02

StringBuffer has a char[] in which it keeps the strings that you append to it. The amount of memory currently allocated to that buffer is the capacity. The amount currently used is the length.

查看更多
老娘就宠你
5楼-- · 2019-01-26 07:05

Taken from the official J2SE documentation

The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.

Its generally length+16, which is the minimum allocation, but once the number of character ie its size exceed the allocated one, StringBuffer also increases its size (by fixed amount), but by how much amount will be assigned,we can't calculate it.

查看更多
Luminary・发光体
6楼-- · 2019-01-26 07:06

Capacity is amount of storage available for newly inserted characters.It is different from length().The length() returns the total number of characters and capacity returns value 16 by default if the number of characters are less than 16.But if the number of characters are more than 16 capacity is number of characters + 16. In this case,no of characters=17 SO,Capacity=17+16=33

查看更多
欢心
7楼-- · 2019-01-26 07:10

The initial capacity of StringBuffer/StringBuilder class is 16. For the first time if the length of your String becomes >16. The capacity of StringBuffer/StringBuilder class increases to 34 i.e [(16*2)+2]

But when the length of your String becomes >34 the capacity of StringBuffer/StringBuilder class becomes exactly equal to the current length of String.

查看更多
登录 后发表回答