介绍
A mutable sequence of characters.
示例
xxxxxx
结构
源码
成员变量
/**
* The value is used for character storage.
*/
char[] value;
/**
* The count is the number of characters used.
*/
int count;
/**
* The maximum size of array to allocate.
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
构造方法
/**
* Creates an AbstractStringBuilder of the specified capacity.
*/
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
成员方法
/**
* Appends the specified string to this character sequence.
*/
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;
}
/**
* Ensures that the capacity is at least equal to the specified minimum.
*/
private void ensureCapacityInternal(int minimumCapacity) {
if (minimumCapacity - value.length > 0) {
value = Arrays.copyOf(value, newCapacity(minimumCapacity));
}
}
/**
* Returns a capacity at least as large as the given minimum capacity.
*/
private int newCapacity(int minCapacity) {
int newCapacity = (value.length << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
private int hugeCapacity(int minCapacity) {
if (Integer.MAX_VALUE - minCapacity < 0) { // overflow
throw new OutOfMemoryError();
}
return (minCapacity > MAX_ARRAY_SIZE)
? minCapacity : MAX_ARRAY_SIZE;
}
面试
Stringbuffer 与 Stringbuilder 的区别?
1、StringBuffer:线程安全,StringBuilder:线程不安全,因为 StringBuffer 的所有公开方法都是 synchronized 修饰的。
2、都继成了 AbstractStringBuilder 这个抽象类,实现了 CharSequence 接口。
3、初始容量都是16和扩容机制都是"旧容量*2+2"。
4、StringBuffer 比 StringBuilder 多了一个 toStringCache 字段,用来在 toString方法中进行缓存。