StringBuilder源码分析
-
String,StringBuffer,StringBuilder
// 1.String为什么是不可变的 private final char value[]; // 2.StringBuilder,Buffer为什么可变 private transient char[] toStringCache; // 3.StringBuffer为什么是线程安全的 public synchronized StringBuffer append(String str);
-
// 类的继承实现关系 // StringBuilder -> AbstractStringBuilder -> CharSquence public final class StringBuilder extends AbstractStringBuilder implements java.io.Serializable, CharSequence {
1.字段
/** * The value is used for character storage. */ char[] value; /** * The count is the number of characters used. */ int count;
2.构造方法
public StringBuilder() { super(16); } AbstractStringBuilder(int capacity) { value = new char[capacity]; } public StringBuilder(String str) { super(str.length() + 16); append(str); }
3.add方法
3.1 add(String str)
// 添加方法 public AbstractStringBuilder append(String str) { // 如果为空 if (str == null) return appendNull(); int len = str.length(); ensureCapacityInternal(count + len); str.getChars(0, len, value, count); count += len; return this; } private AbstractStringBuilder appendNull() { int c = count; // 确保容量 ensureCapacityInternal(c + 4); final char[] value = this.value; value[c++] = 'n'; value[c++] = 'u'; value[c++] = 'l'; value[c++] = 'l'; count = c; return this; } // 确保容量的方法 private void ensureCapacityInternal(int minimumCapacity) { // overflow-conscious code // 如果所需容量大于数组长度,则扩容 if (minimumCapacity - value.length > 0) { value = Arrays.copyOf(value, newCapacity(minimumCapacity)); } }
来源:oschina
链接:https://my.oschina.net/u/4182062/blog/3168376