String系列——StringBuilder & StringBuffer关键源码解析

文章来自:http://www.cnblogs.com/xiaoxuetu/ 

      在前面的博文《小学徒成长系列—String关键源码解析》和《小学徒进阶系列—JVM对String的处理》中,我们讲到了关于String的常用方法以及JVM对字符串常量String的处理。

      但是在Java中,关于字符串操作的类还有两个,它们分别是StringBuilder和StringBuffer。我们先来就讲解一下String类和StringBuilder、StringBuffer的联系吧。

String、StringBuilder、StringBuffer的异同点

    结合之前写的博文,我们对这三个常用的类的异同点进行分析:

    异:

        1>String的对象是不可变的;而StringBuilder和StringBuffer是可变的。

        2>StringBuilder不是线程安全的;而StringBuffer是线程安全的

        3>String中的offset,value,count都是被final修饰的不可修改的;而StringBuffer和StringBuilder中的value,count都是继承自AbstractStringBuilder类的,没有被final修饰,说明他们在运行期间是可修改的,而且没有offset变量。

    同:

        三个类都是被final修饰的,是不可被继承的。

StringBuilder和StringBuffer的构造方法

         其实StringBuilder和StringBuffer的构造方法类型是一样的,里面都是通过调用父类的构造方法进行实现的,在这里,我主要以StringBuilder为例子讲解,StringBuffer就不重复累赘的讲啦。

    1>构建一个初始容量为16的默认的字符串构建

public StringBuilder() {
    super(16);
}
        从构造方法中我们看到,构造方法中调用的是父类AbstractStringBuilder中的构造方法,我们来看看,父类中的构造方法:
/**
 * 构造一个不带任何字符的字符串生成器,其初始容量由 capacity 参数指定。
 * @params capacity 数组初始化容量
 */
AbstractStringBuilder(int capacity) {
    value = new char[capacity];
}
        这个构造方法说明的是,创建一个初始容量由 capacity 参数指定的字符数组,而子类中传过来的是16,所以创建的就是初始容量为16的字符数组

    2>构造一个不带任何字符的字符串生成器,其初始容量由 capacity 参数指定。

public StringBuilder(int capacity) {
    super(capacity);
}
        这个构造方法调用的跟上面1>的构造方法是同一个的,只是这里子类中的初始化容量由用户决定。

    3>构造一个字符串生成器,并初始化为指定的字符串内容。该字符串生成器的初始容量为 16 加上字符串参数的长度。

public StringBuilder(String str) {
    super(str.length() + 16);
    append(str);
}
        这个构造方法首先调用和1>一样的父类构造方法,然后再调用本类中的append()方法将字符串str拼接到本对象已有的字符串之后。

    4>构造一个字符串生成器,包含与指定的 CharSequence 相同的字符。该字符串生成器的初始容量为 16 加上 CharSequence 参数的长度。

public StringBuilder(CharSequence seq) {
    this(seq.length() + 16);
    append(seq);
}
        嗯,这个构造方法,大家一看就知道跟上面的差不多啦,我就不介绍啦。

StringBuilder常用的方法

        在StringBuilder中,很多方法最终都是进行一定的逻辑处理,然后通过调用父类AbstractStringBuilder中的方法进行实现的。

1>append(String str)

        从下面的代码中我们可以看到,他是直接调用父类的append方法进行实现的。

public StringBuilder append(String str) {
    super.append(str);
    return this;
}
        下面我们再看下父类AbstractStringBuilder中的append方法是怎么写的
public AbstractStringBuilder append(String str) {
    //注意,当str的值为nul时,将会在当前字符串对象后面添加上Null字符串
    if (str == null) str = "null";
    //获取需要添加的字符串的长度
    int len = str.length();
    //判断添加后的字符串对象是否超过容量,若是,扩容
    ensureCapacityInternal(count + len);
    //将str中的字符串复制到value数组中
    str.getChars(0, len, value, count);
    //更新当前字符串对象的字符串长度
    count += len;
    return this;
}

2> ensureCapacityInternal

        下面我们看下,他每次拼接字符串的时候,是怎样进行扩容的:

/**
  * This method has the same contract as ensureCapacity, but is
  * never synchronized.
  */
private void ensureCapacityInternal(int minimumCapacity) {
    // overflow-conscious code
    // 如果需要扩展到的容量比当前字符数组长度要大
    // 那么就正常扩容
    if (minimumCapacity - value.length > 0)
        expandCapacity(minimumCapacity);
}

/**
 * This implements the expansion semantics of ensureCapacity with no
 * size check or synchronization.
 */
void expandCapacity(int minimumCapacity) {
    // 初始化新的容量大小为当前字符串长度的2倍加2
    int newCapacity = value.length * 2 + 2;
    // 如果新容量大小比传进来的最小容量还要小
    // 就是用最小的容量为新数组的容量
    if (newCapacity - minimumCapacity < 0)
        newCapacity = minimumCapacity;
    // 如果新的容量或者最小容量小于0
    // 抛异常并且讲新容量设置成Integer最能存储的最大值
    if (newCapacity < 0) {
        if (minimumCapacity < 0) // overflow
            throw new OutOfMemoryError();
        newCapacity = Integer.MAX_VALUE;
    }
    // 创建容量大小为newCapacity的新数组
    value = Arrays.copyOf(value, newCapacity);
}

3>append(StringBuffer sb) 

        从这里我们可以看到,它又是调用父类的方法进行拼接的。

public StringBuilder append(StringBuffer sb) {
    super.append(sb);
    return this;
}
        继续看父类中的拼接方法:
// Documentation in subclasses because of synchro difference
public AbstractStringBuilder append(StringBuffer sb) {
    // 如果sb的值为null,这里就会为字符串添加上字符串“null”
    if (sb == null)
        return append("null");
    // 获取需要拼接过来的字符串的长度
    int len = sb.length();
    // 扩容当前兑现搞定字符数组容量
    ensureCapacityInternal(count + len);
    // 进行字符串的拼接
    sb.getChars(0, len, value, count);
    // 更新当前字符串对象的长度变量
    count += len;
    return this;
}

4>public StringBuilder delete(int start, int end) 

        删除从start开始到end结束的字符(包括start但不包括end)
public StringBuilder delete(int start, int end) {
    super.delete(start, end);
    return this;
}
        是的,又是调用父类进行操作的。
/**
 * Removes the characters in a substring of this sequence.
 * The substring begins at the specified {@code start} and extends to
 * the character at index {@code end - 1} or to the end of the
 * sequence if no such character exists. If
 * {@code start} is equal to {@code end}, no changes are made.
 *
 * @param      start  The beginning index, inclusive.
 * @param      end    The ending index, exclusive.
 * @return     This object.
 * @throws     StringIndexOutOfBoundsException  if {@code start}
 *             is negative, greater than {@code length()}, or
 *             greater than {@code end}.
 */
public AbstractStringBuilder delete(int start, int end) {
    // 健壮性的检查
    if (start < 0)
        throw new StringIndexOutOfBoundsException(start);
    if (end > count)
        end = count;
    if (start > end)
        throw new StringIndexOutOfBoundsException();
    // 需要删除的长度
    int len = end - start;
    if (len > 0) {
        // 进行复制,将被删除的元素后面的复制到前面去
        System.arraycopy(value, start+len, value, start, count-end);
        // 更新字符串长度
        count -= len;
    }
    return this;
}
        其实看了那么多,我们也很容易发现,不管是String类还是现在博文中的StringBuilder和StringBuffer,底层实现都用到了Arrays.copyOfRange(original, from, to);和System.arraycopy(src, srcPos, dest, destPos, length);这两个方法实现的。

        在看完上面那段源代码之后,我突然想到了一个问题,就是如果需要剩下的字符个数少于需要被覆盖的字符个数时怎么办,看下面的代码:

import java.util.Arrays;

public class StringBuilderTest {
    public static void main(String[] args) {
        char[] src = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
        int start = 4;
        int end = 5;
        int len = end - start;
        if (len > 0) {
            //进行复制,将被删除
            System.arraycopy(src, start+len, src, start, src.length-end);
        }
        System.out.println(src);

        StringBuilder stringBuilder = new StringBuilder("abcdefg");
        stringBuilder.delete(4, 5);
        System.out.println(stringBuilder);
    }
}
结果输出了:

        奇怪,为什么StringBuilder可以输出abcdefg而我的会多了一个g呢?原因是在StringBuilder中的toString方法中重新创建了一个有效数字为count的,也就是说值为abcdefg的字符串对象,如下代码:

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

5>public StringBuilder replace(int start, int end, String str)

        关于这个方法,因为是直接调用父类中的方法进行实现的,所以我们继续直接看父类中的方法吧:
/**
 * Replaces the characters in a substring of this sequence
 * with characters in the specified <code>String</code>. The substring
 * begins at the specified <code>start</code> and extends to the character
 * at index <code>end - 1</code> or to the end of the
 * sequence if no such character exists. First the
 * characters in the substring are removed and then the specified
 * <code>String</code> is inserted at <code>start</code>. (This
 * sequence will be lengthened to accommodate the
 * specified String if necessary.)
 *
 * @param      start    The beginning index, inclusive.
 * @param      end      The ending index, exclusive.
 * @param      str   String that will replace previous contents.
 * @return     This object.
 * @throws     StringIndexOutOfBoundsException  if <code>start</code>
 *             is negative, greater than <code>length()</code>, or
 *             greater than <code>end</code>.
 */
public AbstractStringBuilder replace(int start, int end, String str) {
    // 健壮性的检查
    if (start < 0)
        throw new StringIndexOutOfBoundsException(start);
    if (start > count)
        throw new StringIndexOutOfBoundsException("start > length()");
    if (start > end)
        throw new StringIndexOutOfBoundsException("start > end");

    if (end > count)
        end = count;

    // 获取需要添加的字符串的长度
    int len = str.length();
    // 计算新字符串的长度
    int newCount = count + len - (end - start);
    // 对当前对象的数组容量进行扩容
    ensureCapacityInternal(newCount);
    // 进行数组的中的元素移位,从而空出足够的空间来容纳需要添加的字符串
    System.arraycopy(value, end, value, start + len, count - end);
    // 将str复制到value中
    str.getChars(value, start);
    // 更新字符串长度
    count = newCount;
    return this
}

6>public StringBuilder insert(int offset, String str)

        在offset位置插入字符串str,他的实现也是通过父类进行实现的,继续看父类中的相应方法:
/**
 * Inserts the string into this character sequence.
 * <p>
 * The characters of the {@code String} argument are inserted, in
 * order, into this sequence at the indicated offset, moving up any
 * characters originally above that position and 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 inserted into this sequence.
 * <p>
 * The character at index <i>k</i> in the new character sequence is
 * equal to:
 * <ul>
 * <li>the character at index <i>k</i> in the old character sequence, if
 * <i>k</i> is less than {@code offset}
 * <li>the character at index <i>k</i>{@code -offset} in the
 * argument {@code str}, if <i>k</i> is not less than
 * {@code offset} but is less than {@code offset+str.length()}
 * <li>the character at index <i>k</i>{@code -str.length()} in the
 * old character sequence, if <i>k</i> is not less than
 * {@code offset+str.length()}
 * </ul><p>
 * The {@code offset} argument must be greater than or equal to
 * {@code 0}, and less than or equal to the {@linkplain #length() length}
 * of this sequence.
 *
 * @param      offset   the offset.
 * @param      str      a string.
 * @return     a reference to this object.
 * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
 */
public AbstractStringBuilder insert(int offset, String str) {
    if ((offset < 0) || (offset > length()))
        throw new StringIndexOutOfBoundsException(offset);
    if (str == null)
        str = "null";
    int len = str.length();
    ensureCapacityInternal(count + len);
    // 将字符串后移为插入的字符串留充足的空间
    System.arraycopy(value, offset, value, offset + len, count - offset);
    // 将str复制到value数组中  
    str.getChars(value, offset);
    // 更新当前对象中记录的长度
    count += len;
    return this;
}

7>indexOf(String str)

        其实这个的实现主要是借助了String对象的indexOf方法来实现的,具体可以参考博文:《小学徒成长系列—String关键源码解析》这里就不详细进行讲解了:
/**
 * @throws NullPointerException {@inheritDoc}
 */
public int indexOf(String str) {
    return indexOf(str, 0);
}
        调用了同一个类中的indexOf方法:
/**
 * @throws NullPointerException {@inheritDoc}
 */
public int indexOf(String str, int fromIndex) {
    //调用了String类中的静态方法indexOf
    return String.indexOf(value, 0, count,
                          str.toCharArray(), 0, str.length(), fromIndex);
}
        String.indexOf()方法是默认权限的,也就是只有与他同包的情况下才能够进行访问这个方法。

8> lastIndexOf()

        lastIndexOf()方法跟indexOf()差不多,调用了String.lastIndexOf()方法进行实现,再次不重复说明。

9> public StringBuilder reverse()

        我们经常进行字符串的逆转,面试的时候也有经常问到,那么实际上在jdk中式怎么完成这些操作的呢?

        首先我们看下StringBuilder中的reverse方法():

public StringBuilder reverse() {
    //调用父类的reverse方法
    super.reverse();
    return this;
}
        一般情况下,如果让我们来进行逆转,会怎么写呢?我想很多人都会像下面那样子写吧:
public String reverse(char[] value){
    //折半,从中间开始置换
    for (int i = (value.length - 1) >> 1; i >= 0; i--){
       char temp = value[i];
       value[i] = value[value.length - 1 - i];
       value[value.length - 1 - i] = temp;
    }
    return new String(value);
}
        确实很简单,但是一个完整的 Unicode 字符叫代码点CodePoint,而一个 Java char 叫 代码单元 code unit。如果String 对象以UTF-16保存 Unicode 字符,需要用2个字符表示一个超大字符集的汉字,则这种表示方式称之为 Surrogate,第一个字符叫Surrogate High,第二个就是 Surrogate Low。所以在JDK中也加入了判断一个char是否是Surrogate区的字符:
/**
 * Causes this character sequence to be replaced by the reverse of
 * the sequence. If there are any surrogate pairs included in the
 * sequence, these are treated as single characters for the
 * reverse operation. Thus, the order of the high-low surrogates
 * is never reversed.
 *
 * Let <i>n</i> be the character length of this character sequence
 * (not the length in <code>char</code> values) just prior to
 * execution of the <code>reverse</code> method. Then the
 * character at index <i>k</i> in the new character sequence is
 * equal to the character at index <i>n-k-1</i> in the old
 * character sequence.
 *
 * <p>Note that the reverse operation may result in producing
 * surrogate pairs that were unpaired low-surrogates and
 * high-surrogates before the operation. For example, reversing
 * "\uDC00\uD800" produces "\uD800\uDC00" which is
 * a valid surrogate pair.
 *
 * @return  a reference to this object.
 */
public AbstractStringBuilder reverse() {
    // 默认没有存储到Surrogate区的字符
    boolean hasSurrogate = false;
    int n = count - 1;
    // 折半,遍历并且首尾相应位置置换
    for (int j = (n-1) >> 1; j >= 0; --j) {
        char temp = value[j];
        char temp2 = value[n - j];
        if (!hasSurrogate) {
            // 判断一个char是否是Surrogate区的字符
            hasSurrogate = (temp >= Character.MIN_SURROGATE && temp <= Character.MAX_SURROGATE)
                || (temp2 >= Character.MIN_SURROGATE && temp2 <= Character.MAX_SURROGATE);
        }
        // 首尾值置换
        value[j] = temp2;
        value[n - j] = temp;
    }

    // 如果含有Surrogate区的字符
    if (hasSurrogate) {
        // Reverse back all valid surrogate pairs
        for (int i = 0; i < count - 1; i++) {
            char c2 = value[i];
            if (Character.isLowSurrogate(c2)) {
                char c1 = value[i + 1];
                if (Character.isHighSurrogate(c1)) {
                    //下面这行代码相当于
                    //value[i]=c1; i=i+1;
                    value[i++] = c1;
                    value[i] = c2;
                }
            }
        }
    }
    return this;
}

StringBuffer的常用方法

        前面我们知道StringBuffer相当于StringBuilder来说是线程安全的,所以再StringBuffer中,所有的方法都加了同步synchronized,例如append(String str)方法:
public synchronized StringBuffer append(String str) {
    super.append(str);
    return this;
}
        具体内部实现就不详细说明啦,跟StringBuilder是一样的,大部分都是调用AbstractStringBuilder进行实现的。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值