Monday, February 10, 2014

Best Practices Java - StringBuffer Part 2

It's good to define string as StringBuffer for most of the common use(Refer Part 1). We will now see how StringBuffer enlarge itself, as it is mutable.

If you are just calling the default creation of StringBuffer, the following code will get called(default size of 16 characters).
   super(16);
}



StringBuffer takes its data structure from its parent class which is AbstractStringBuilder, something like:


abstract class AbstractStringBuilder implements AppendableCharSequence {
            char value[]; // actual character storage.
int count; // count the no. of char's used.



This is how expandCapacity has been written in JDK:


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);
}




This expandCapacity() has been called from append() method of StringBuffer. Most of the methods of StringBuffer are synchronized as expected.

For more understanding, you can see the openJDK source code. 

 


No comments: