StringBuilder如果不指定初始容量,默认容量大小是多少,扩容是每次容量大小*2吗?
/**
* Returns a capacity at least as large as the given minimum capacity.
* Returns the current capacity increased by the same amount + 2 if
* that suffices.
* Will not return a capacity greater than {@code MAX_ARRAY_SIZE}
* unless the given minimum capacity is greater than that.
*
* @param minCapacity the desired minimum capacity
* @throws OutOfMemoryError if minCapacity is less than zero or
* greater than Integer.MAX_VALUE
*/
private int newCapacity(int minCapacity) {
// overflow-conscious code
int newCapacity = (value.length << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
左移一位,然后 + 2,相当于*2 再 +2,我这是Java8
/**
* Constructs a string builder with no characters in it and an
* initial capacity of 16 characters.
*/
public StringBuilder() {
super(16);
}
/**
* Constructs a string builder with no characters in it and an
* initial capacity specified by the {@code capacity} argument.
*
* @param capacity the initial capacity.
* @throws NegativeArraySizeException if the {@code capacity}
* argument is less than {@code 0}.
*/
public StringBuilder(int capacity) {
super(capacity);
}
不给的话默认容量是16
StringBuilder
的初始容量和扩容规则在 Java 中有一些特定的定义:
StringBuilder
对象时不指定初始容量,则默认为 16 个字符。这意味着,如果你使用 new StringBuilder()
,它的初始容量就是 16 字符。StringBuilder
中的内容超过当前容量时,它会进行扩容。扩容的规则是将当前容量加倍,这实际上是 当前容量 * 2。这种设计使得 StringBuilder
在字符串连接和修改时能够高效地管理内存,避免频繁的内存分配。如果你知道将要使用的字符串的最大长度,可以在创建 StringBuilder
时指定一个合适的初始容量,以提高性能。