String
源码分析:1
2
3
4
5
6
7
8
9
10
11
12
13
14public String() {
        this.value = "".value;
    }
    /**
    * Initializes a newly created {@code String} object so that it represents
    * the same sequence of characters as the argument; in other words, the
    * newly created string is a copy of the argument string. Unless an
    * explicit copy of {@code original} is needed, use of this constructor is
    * unnecessary since Strings are immutable.
    *
    * @param  original
    *         A {@code String}
    */
String类中每一个看起来会修改String值得方法,实际上都是创建了一个全新的String对象。每当把String对象作为方法的参数时,都会复制一份引用,而该引用所指的对象其实一直待在单一的物理位置上。这就是为什么我们说String类是不可变的(immutable)。
StringBuffer
源码分析:
定义:1
2
3
4
5
6public final class StringBuffer
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{
    ...
}
StringBuffer类被final修饰,因此不能继承。
此类的父类是AbstractStringBuilder,AbstractStringBuilder类中具体实现了可变字符序列的一系列操作,比如append()、insert()、delete()、replace()、charAt()方法等。
此类实现了两个接口,Serializable表示该类的对象可以被序列化,CharSequence的接口提供了几个对字符序列进行只读访问的方法,例如length()、charAt()、subSequence()、toString()方法等。
主要变量:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17/**
     * A cache of the last value returned by toString. Cleared
     * whenever the StringBuffer is modified.
     */
    private transient char[] toStringCache;
// AbstractStringBuilder.java
/**
     * The value is used for character storage.
     */
    char[] value;
/**
     * The count is the number of characters used.
     */
    int count;
- toStringCache用来缓存toString()方法返回的最近一次的value数组中的字符。当修改StringBuffer对象时会被清除。
 value用来存储字符序列中的字符。这是一个动态数组,当存储容量不足时,会对它进行扩容。
1
2
3AbstractStringBuilder(int capacity) {
value = new char[capacity];
}count表示value数组中已存储的字符数。
StringBuffer类将所有操作字符序列的方法都添加了 synchronized 关键字来修饰,因此,StringBuffer类是线程安全的。
StringBuilder
StringBuilder和StringBuffer的源码中,定义和操作几乎都是一样的,唯一的区别是StringBuffer是线程安全的,在单线程的情况下StringBuilder比StringBuffer要快。