结论

相同点:

  • 都继承自AbstractStringBuilder
  • 都是可变长字符串,底层都是调用的AbstractStringBuilderchar[] value;数组来存储,
  • stringBufferstringBuilder默认长度都是16。长度不够会进行扩容。

不同点:

  • stringBuffer是线程安全的,每个公开方法上都有加锁synchronized
  • stringBuilder不是线程安全的,公开方法没有加锁。
  • stringBuffer里面有一个缓存toStringCache,这是一个优化,在每次添加其他操作前都会将该缓存置为nullstringBuilder没有缓存

源码

stringBuilder关键源码

public final class StringBuilder
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{}
    public StringBuilder() {
        super(16);
    }
    public StringBuilder(int capacity) {
        super(capacity);
    }
    public StringBuilder(String str) {
        super(str.length() + 16);
        append(str);
    }

    @Override
    public StringBuilder append(Object obj) {
        return append(String.valueOf(obj));
    }

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

toString

    @Override
    public String toString() {
        // Create a copy, don't share the array
        return new String(value, 0, count);
    }

stringBuffer关键源码

 public final class StringBuffer
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{}
    public StringBuffer() {     // stringbuffer默认容量是16,也可以自己指定
        super(16);
    }
    public StringBuffer(int capacity) {
        super(capacity);
    }
   public StringBuffer(String str) {
        super(str.length() + 16);
        append(str);
    }

    @Override
    public synchronized int length() {
        return count;
    }

    @Override
    public synchronized int capacity() {
        return value.length;
    }

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

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

toString

    @Override
    public synchronized String toString() {
        if (toStringCache == null) {
            toStringCache = Arrays.copyOfRange(value, 0, count);
        }
        return new String(toStringCache, true);
    }

分类: java

站点统计

  • 文章总数:315 篇
  • 分类总数:20 个
  • 标签总数:193 个
  • 运行天数:1156 天
  • 访问总数:40499 人次

浙公网安备33011302000604

辽ICP备20003309号