阅读 37

String、StringBuilder和StringBuffer的区别浅谈

String、StringBuilder和StringBuffer的区别浅谈

继承结构

在这里插入图片描述 可以看出三者之间共同的接口,实现的方法大部分都一样,只是形式不同。

源码

接下来看看它们的部分源码 String

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;

    /**
     * Class String is special cased within the Serialization Stream Protocol.
     *
     * A String instance is written into an ObjectOutputStream according to
     * <a href="{@docRoot}/../platform/serialization/spec/output.html">
     * Object Serialization Specification, Section 6.2, "Stream Elements"</a>
     */
    private static final ObjectStreamField[] serialPersistentFields =
        new ObjectStreamField[0];

    /**
     * Initializes a newly created {@code String} object so that it represents
     * an empty character sequence.  Note that use of this constructor is
     * unnecessary since Strings are immutable.
     */
    public String() {
        this.value = "".value;
    }
 ...
 }
复制代码

StringBuffer

@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;
}
复制代码

StringBuilder

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

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

AbstractStringBuilder

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;
	...
}
复制代码

从以上的源码可以等出: String的value是不可变型 StringBuffer和StringBuiler的value是可变类型 StringBuffer修改字符数组是加锁的,而StringBuiler不加锁

总结

  1. String、StringBuilder和StringBuffer都实现CharSequence接口
  2. String是不可变类型,它的成员变量是private final,而且没有提供修改变量的方法
  3. String频繁的更换字符,会造成大量的堆内存垃圾
  4. StringBuffer和StringBuiler的value是可变类型, 适用于字符串频繁修改的场景
  5. StringBuffer方法加锁,线程安全,操作变慢
  6. StringBuilder方法不加锁,线程不安全,操作快
文章分类
后端
文章标签