StringBuffer and StringBuilder
What is it? string buffers
Working principle:
Pre-Request a piece of space in memory to accommodate the sequence of characters, and automatically expand to accommodate more character sequences if the reserved space is not sufficient
The difference between StringBuffer, StringBuilder, and string:
String is an immutable sequence of characters that stores strings in a constant pool
StringBuffer the bottom layer is a char array, but the array is mutable and can be automatically enlarged
Public Final classStringBufferextendsAbstractstringbuilderImplementsjava.io.Serializable, charsequence{/*** A Cache of the last value returned by toString. Cleared * Whenever the StringBuffer is modified. */ Private transient Char[] tostringcache; /*** Constructs a string buffer with no characters in it and an * initial capacity of characters. */ PublicStringBuffer () {Super(16);//The default capacity is } PublicStringBuffer (intcapacity) { Super(capacity); } PublicStringBuffer (String str) {Super(Str.length () + 16); Append (str); }}
The default capacity of StringBuilder and StringBuffer is 16
Abstract class Implements appendable, charsequence { /** * The value is used for character storage. */ Char [] value; /** }
Inside is a char array, then the array is fixed, the length will not change, then the automatic expansion is what? is to build a new array, copy the original array data, so it is more time consuming memory,
It is best to predict the required capacity when creating objects of these two classes, create objects in a specified capacity, and improve efficiency by reducing the copying of arrays.
Java Common Classes