StringBuilder由final修饰,该类不可被继承。
StringBuilder是AbstractStringBuilder的子类。
StringBuilder的无参构造方法调用了父类的有参构造方法,可以看出默认的容量为16,也就是把value数组的长度设置为16.
public StringBuilder() {
super(16);
}
/**
* Constructs a string builder with no characters in it and an
* initial capacity specified by the {@code capacity} argument.
*
* @param capacity the initial capacity.
* @throws NegativeArraySizeException if the {@code capacity}
* argument is less than {@code 0}.
*/
当然也可以使用有参的构造方法设置容量
public StringBuilder(int capacity) {
super(capacity);
}
/**
* Constructs a string builder initialized to the contents of the
* specified string. The initial capacity of the string builder is
* {@code 16} plus the length of the string argument.
*
* @param str the initial contents of the buffer.
*/
参数为String的构造方法,默认容量为传入String的长度再加上16;
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}
对于append方法而言,都是调用的父类AbstractStringBuilder的方法
@Override
public StringBuilder append(Object obj) {
return append(String.valueOf(obj));
}
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
public StringBuilder append(StringBuffer sb) {
super.append(sb);
return this;
}
@Override
public StringBuilder append(CharSequence s) {
super.append(s);
return this;
}
toString方法返回一个新的String,
@Override
public String toString() {
// Create a copy, don't share the array
return new String(value, 0, count);
}