Note: Based on jdk11
AbstractStringBuilder
Variable Abstract string creation class
The following interfaces are implemented:
1. Appendable the implementation class of this interface can splice character sequences or single characters. Thread safety is not guaranteed, whether it is implemented by the implementation class. Format using java.util.Formatter, must implement class for appendable 2. CharSequence
Several important member variables:
/** * The byte array of string storage data. The capacity can be specified during initialization. The default value is 16 */ byte[] value; /** * Code 0 is Latin1 1 is Utf-16 */ byte coder; /** * Actual length of current string */ int count; private static final byte[] EMPTYVALUE = new byte[0]; /** * byte [] Maximum length limit, exceeding VM limit length will cause OOM */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
Several important methods:
1. Returns the actual length of the current string, count public int length() { return count; } 2. Return string capacity public int capacity() { return value.length >> coder; } 3. Expansion, byte array copy public void ensureCapacity(int minimumCapacity) { if (minimumCapacity > 0) { ensureCapacityInternal(minimumCapacity); } } private void ensureCapacityInternal(int minimumCapacity) { // overflow-conscious code int oldCapacity = value.length >> coder; if (minimumCapacity - oldCapacity > 0) { value = Arrays.copyOf(value, newCapacity(minimumCapacity) << coder); } } private int newCapacity(int minCapacity) { // overflow-conscious code int oldCapacity = value.length >> coder; int newCapacity = (oldCapacity << 1) + 2; if (newCapacity - minCapacity < 0) { newCapacity = minCapacity; } int SAFE_BOUND = MAX_ARRAY_SIZE >> coder; return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0) ? hugeCapacity(minCapacity) : newCapacity; } private int hugeCapacity(int minCapacity) { int SAFE_BOUND = MAX_ARRAY_SIZE >> coder; int UNSAFE_BOUND = Integer.MAX_VALUE >> coder; if (UNSAFE_BOUND - minCapacity < 0) { // overflow throw new OutOfMemoryError(); } return (minCapacity > SAFE_BOUND) ? minCapacity : SAFE_BOUND; }
StringBuffer
Thread safe AbstractStringBuilder implementation class
Several important methods:
1. toString() uses the cache mechanism. When toString() is called for the first time, the copy of the real-time generated string will be saved in toStringCache. The next call will return directly. If there is any change, toStringCache will be set to null
StringBuilder
Non thread safe AbstractStringBuilder implementation class
Several important methods:
1. toString() creates a string copy in real time and returns