引言
StringBuffer和StringBuilder的构造方法各有四种构造方法,它们各自的构造方法总体原理上是一致的,细微之处有一个缓存区的置空操作。简单来讲可以把他们的构造方法理解成相同的。
构造方法无参构造/**
* Constructs a string buffer with no characters in it and an
* initial capacity of 16 characters.
*/
public StringBuffer() {
super(16);
}/**
* Constructs a string builder with no characters in it and an
* initial capacity of 16 characters.
*/
public StringBuilder() {
super(16);
}
StringBuffer和StringBuilder的无参构造方法继承的是AbstractStringBuilder抽象类中的AbstractStringBuilder(int capacity)方法。/**
* Creates an AbstractStringBuilder of the specified capacity.
*/
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
AbstractStringBuilder(int capacity)方法底层是一个默认容量为capacity=16的字符数组,由此可以知道StringBuffer和StringBuilder无参构造方法构造出的对象的初始容量为16,可以用capacity()方法查看。System.out.println(stringBuilder.capacity());
System.out.println(stringBuffer.capacity());有参构造① 自定义容量
构造一个容量自定义的StringBuffer或StringBuilder对象,传入int 类型的capacity自定义容量。/**
* Constructs a string buffer with no characters in it and
* the specified initial capacity.
*
* @param capacity the initial capacity.
* @exception NegativeArraySizeException if the {@code capacity}
* argument is less than {@code 0}.
*/
public St