重讀StringBuffer與StringBuilder源碼

StringBuffer類的定義——重點final,說明很多性質和String類似不可變
繼承自AbstractStringBuilder

public final class StringBuffer
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{……

無參構造函數,潛臺詞默認初始容量爲16


    /**
     * Constructs a string buffer with no characters in it and an
     * initial capacity of 16 characters.
     */
    public StringBuffer() {
        super(16);
    }

指定大小的構造函數

 /**
     * 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 StringBuffer(int capacity) {
        super(capacity);
    }

super(capacity)的實現,底層是char數組

 /**
     * Creates an AbstractStringBuilder of the specified capacity.
     */
    AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }

指定字符串的構造函數,潛臺詞:容量爲串的長度+16

  /**
     * Constructs a string buffer initialized to the contents of the
     * specified string. The initial capacity of the string buffer is
     * {@code 16} plus the length of the string argument.
     *
     * @param   str   the initial contents of the buffer.
     */
    public StringBuffer(String str) {
        super(str.length() + 16);
        append(str);
    }

append方法

 @Override
    public synchronized StringBuffer append(String str) {
        toStringCache = null;
        super.append(str);
        return this;
    }

重點synchronized:線程安全的,實際實現還是要看父類

父類的實現:

  /**
     * Appends the specified string to this character sequence.
     * <p>
     * The characters of the {@code String} argument are appended, in
     * order, increasing the length of this sequence by the length of the
     * argument. If {@code str} is {@code null}, then the four
     * characters {@code "null"} are appended.
     * <p>
     * Let <i>n</i> be the length of this character sequence just prior to
     * execution of the {@code append} method. Then the character at
     * index <i>k</i> in the new character sequence is equal to the character
     * at index <i>k</i> in the old character sequence, if <i>k</i> is less
     * than <i>n</i>; otherwise, it is equal to the character at index
     * <i>k-n</i> in the argument {@code str}.
     *
     * @param   str   a string.
     * @return  a reference to this object.
     */
    public AbstractStringBuilder append(String str) {
        if (str == null)
            return appendNull();
        int len = str.length();
        ensureCapacityInternal(count + len);
        str.getChars(0, len, value, count);// 從0開始,到當前數組長度,進行拷貝
        count += len;
        return this;
    }

分析ensureCapacityInternal(count + len);目的是爲了確保容量至少等於指定的最小值


  /**
   * For positive values of {@code minimumCapacity}, this method
   * behaves like {@code ensureCapacity}, however it is never
   * synchronized.
   * If {@code minimumCapacity} is non positive due to numeric
   * overflow, this method throws {@code OutOfMemoryError}.
   */
  private void ensureCapacityInternal(int minimumCapacity) {
      // overflow-conscious code
      if (minimumCapacity - value.length > 0) {
          value = Arrays.copyOf(value,
                  newCapacity(minimumCapacity));
      }
  }

再看StringBuilder,幾乎一樣,不同處是append方法,沒有采取同步措施


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

總結:StringBuilder/StringBuffer均繼承自AbstractStringBuilder,大多底層方法均由AbstractStringBuilder實現,默認容量均爲16
不同之處在於:StringBuffer線程安全,而StringBuilder線程不安全

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章