面试题04-String-StringBuffer-StringBuilder

  • String是final修饰的,不可变,每次操作都会产生新的String对象
public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence,
               Constable, ConstantDesc {
    ......
}
  • StringBuffer和StringBuilder都是再原对象上操作
  • StringBuffer是线程安全的,StringBuilder是线程不安全的
  • StringBuffer方法都是synchronized修饰的
public final class StringBuffer
        extends AbstractStringBuilder
        implements java.io.Serializable, Comparable<StringBuffer>, CharSequence {
    /* ...... */
    @Override
    public synchronized int compareTo(StringBuffer another) {
        return super.compareTo(another);
    }

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

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


    @Override
    public synchronized void ensureCapacity(int minimumCapacity) {
        super.ensureCapacity(minimumCapacity);
    }

    /* ...... */
}
  • 性能:StringBuilder>StringBuffer>String
  • 使用场景:

经常需要改变字符串内容时使用后面两个
优先使用StringBuilder,多线程使用共享变量时使用StringBuffer

上一篇:synchronized实现原理与应用


下一篇:synchronized关键字介绍(秋招篇)——上