When using StringBuffer in java, I'm wondering how the append function is implemented when it needs to reallocate space.
For example, if I append a string longer than the currently allocated space, how does it manage this in the details of the method?
The source is included in the JDK download. Just look for the src.zip file (mine is in Program Files (x86)\Java\jdk1.6.0_01\src.zip). After extracting, just go to java/lang and you can examine StringBuffer.java, StringBuilder.java, and AbstractStringBuilder.java.
In this implementation, looks like "expandCapacity" in AbstractStringBuilder calculates the capacity and does an Arrays.copyOf() to expand the buffer. It's also interesting to note that first check is for < 0 to guard against overflow condition.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With