Java源码分析之StringBuffer---A thread-safe, mutable sequence of characters.
源码开头给出的StringBuffer的优点:
1. 可以修改的,也就是说是一个字符串变量
2. 线程安全的,因为部分方法被Synchronized修饰符所修饰.
3. 主要操作:append(添加字符串到末尾)和insert(添加字符串到指定的位置)方法,这两个方法被重载了,所以可以适用任何类类型数据。
sb.append(x)等价于sb.insert(sb.length,x);
4. 可以自动进行扩容
5. 不能给StringBuffer的构造器和方法传null,否则会报空指针错误
6. 作为补充,JDK5中提供了StringBuilder方法,其是单线程的,优先使用StringBuilder方法,因为StringBuilder方法的速度更快,因为他没有Synchronized修饰。
源码分析:
public final class StringBuffer extends AbstractStringBuilder implements java.io.Serializable, CharSequence{ }
StringBuffer方法继承AbstractStringBuilder方法,实现Serializable(序列化)和CharSequence(字节序列)接口
1. 构造方法
/** * 构造一个空的字符串缓冲区,其初始化大小为16个字符 * */ public StringBuffer() { super(16); } /** * * * * @param capacity the initial capacity. * @exception NegativeArraySizeException if the {@code capacity} * argument is less than {@code 0}. */ public StringBuffer(int capacity) { super(capacity); } /** * 用指定的字符串来初始化字符串缓冲区,其大小为16+指定字符串的长度 * * * @param str the initial contents of the buffer. */ public StringBuffer(String str) { super(str.length() + 16); append(str); } /** * Constructs a string buffer that contains the same characters * as the specified {@code CharSequence}. The initial capacity of * the string buffer is {@code 16} plus the length of the * {@code CharSequence} argument. * <p> * If the length of the specified {@code CharSequence} is * less than or equal to zero, then an empty buffer of capacity * {@code 16} is returned. * * @param seq the sequence to copy. * @since 1.5 */ public StringBuffer(CharSequence seq) { this(seq.length() + 16); append(seq); }