Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java StringBuffer append allocation

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?

like image 664
NullPointer0x00 Avatar asked Jan 22 '23 06:01

NullPointer0x00


1 Answers

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);
}
like image 147
doobop Avatar answered Jan 25 '23 22:01

doobop