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 07:14

See: JavaSE 6 java.lang.StringBuffer capacity()

But your assumption is correct:

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

查看更多
冷血范
3楼-- · 2019-01-26 07:14

Internally StringBuffer uses a char array in order to store characters. Capacity is the initial size of that char array.

More INFO can be found from http://download.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html

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

It's the size of internal buffer. As Javadoc says:

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.

查看更多
看我几分像从前
5楼-- · 2019-01-26 07:21

"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."

http://download.oracle.com/javase/1.3/docs/api/java/lang/StringBuffer.html -see capacity() and ensurecapacity()

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

Ivan, just read the documentation for capacity() - it directly answers your question...

查看更多
劫难
7楼-- · 2019-01-26 07:22

From http://download.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html#capacity%28%29

public int capacity()

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

Also from the same document

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

查看更多
登录 后发表回答