StringBuilder

阅读更多
StringBuilder

1.不可继承

public final class StringBuilder extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence


2.内容可变


    /**
     * The value is used for character storage.
     */
    char value[];



3.构造方法

默认构造一个长度为16的char数组

    

    public StringBuilder(int capacity) {
	super(capacity);
    }

    public StringBuilder() {
	super(16);
    }

    public StringBuilder(String str) {
	super(str.length() + 16);
	append(str);
    }



abstract class AbstractStringBuilder implements Appendable, CharSequence {
    /**
     * The value is used for character storage.
     */
    char value[];

    /** 
     * The count is the number of characters used.
     */
    int count;

    /** 
     * This no-arg constructor is necessary for serialization of subclasses.
     */
    AbstractStringBuilder() {
    }

    /** 
     * Creates an AbstractStringBuilder of the specified capacity.
     */
    // 构建一个长度为X的char类型数组
    AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }
}



4.append()


    public StringBuilder append(String str) {
	super.append(str);
        return this;
    }






    public AbstractStringBuilder append(String str) {
	if (str == null) str = "null";
        int len = str.length();
	if (len == 0) return this;
	int newCount = count + len;
	if (newCount > value.length)
	    expandCapacity(newCount);
	str.getChars(0, len, value, count);
	count = newCount;
	return this;
    }

    // 数组拷贝,改变str的内容
    public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
        if (srcBegin < 0) {
            throw new StringIndexOutOfBoundsException(srcBegin);
        }
        if (srcEnd > count) {
            throw new StringIndexOutOfBoundsException(srcEnd);
        }
        if (srcBegin > srcEnd) {
            throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
        }
        System.arraycopy(value, offset + srcBegin, dst, dstBegin,
             srcEnd - srcBegin);
    }

    // 添加新的字符串后的长度大于已有的容量,扩容处理,产生新的对象
    // 扩容的长度,(leng+1)*2
    void expandCapacity(int minimumCapacity) {
	int newCapacity = (value.length + 1) * 2;
        if (newCapacity < 0) {
            newCapacity = Integer.MAX_VALUE;
        } else if (minimumCapacity > newCapacity) {
	    newCapacity = minimumCapacity;
	}
        value = Arrays.copyOf(value, newCapacity);
    }



其他:

1.str = str + str1 ; 或 str+= str1 ;
实质等价于 StringBuilder sb = new StringBuilder(str);sb.append(str1);

但在循环中使用 s+=s1 ;相当于每次都创建一个新的对象;

所以,多次进行字符串拼接操作时改为使用StringBuidler

你可能感兴趣的:(StringBuilder)