【JDK】:java.lang.String、StringBuilder、StringBuffer 源码解析

String

接口和属性

String类是final不可继承的,用来存放字符数组的value[]也是final修饰的,这意味着String类是不可变的,一旦new出来就不能发生改变。因此对一个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,缓存字符串的hashCode
}

构造方法

一般直接使用双引号的方式,默认调用构造方法生成一个String对象。构造方法很多,下面只列出常用的几种:

    // 默认无参构造
    public String() {
        this.value = "".value;
    }

    // 由一个String对象构造 String str = new String("hello");
    public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }

    // 字符数组构造
    public String(char value[]);

    // 字符数组构造,指定偏移量和字符数目
    public String(char value[], int offset, int count);

    // Unicode码数组构造,指定偏移量和字符数目
    public String(int[] codePoints, int offset, int count);

    // 字节数组构造
    public String(byte bytes[]);

    // 字节数组构造,指定偏移量、数目,默认字符集
    public String(byte bytes[], int offset, int length);

    // 字节数组构造,指定偏移量、数目、字符集
    public String(byte bytes[], int offset, int length, Charset charset);

    // StringBuffer 构造,线程安全
    public String(StringBuffer buffer) {
        synchronized(buffer) {
            this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
        }
    }

    // StringBuilder 构造,非线程安全
    public String(StringBuilder builder) {
        this.value = Arrays.copyOf(builder.getValue(), builder.length());
    }

常用方法

equals()和hashCode()

在涉及到比较和排序时,一般的类都需要同时重写equals()和hashCode()方法。String提供了hashCode()方法实现的模板,需要考虑String类中value字符数组中的每一个字符,将计算出的hash(int)缓存在属性hash中。

equals()

    public boolean equals(Object anObject) {
        // 注意!equals方法需要满足自反性、对称性、传递性
        // 首先就要与自身先判断
        if (this == anObject) {   
            return true;
        }
        if (anObject instanceof String) {    // 使用instanceof,如果不是,直接返回false
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {       // 巧妙的代码!
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

hashCode()

    // 计算String的int类型hash码
    // hash = s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[0]
    /* 根据Effective Java第9条中的描述
       使用31是因为31是奇数素数,习惯上都使用素数来计算散列结果。
       使用31可以用移位运算和减法代替乘法,提高效率:
       31 * i == (i << 5) - i
       现代的虚拟机VM都会自动完成这种优化。
    */
    public int hashCode() {
        int h = hash;  // hash缓存,初始为0
        if (h == 0 && value.length > 0) {
            char val[] = value;
            // 考虑所有的字符
            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

length()、isEmpty()、charAt()

String的length()是方法,而数组的length是属性,注意二者的区分。此外与C/C++中的字符串不同,C/C++的字符串一定是以’\0’结尾,length包括了这一个结束符,而Java中的String类中的value字符数组没有该结束符。

    // 字符串长度
    public int length() {
        return value.length;
    }

    public boolean isEmpty() {
        return value.length == 0;
    }

    // 第index位置的字符
    public char charAt(int index) {
        // 注意!索引范围检查
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return value[index];
    }

equalsIgnoreCase()

忽略大小写的字符串比较。技巧:注意三目条件运算符和逻辑运算的使用,能够有效避免冗长的if…else…语句,使代码简洁清晰。

    public boolean equalsIgnoreCase(String anotherString) {
        return (this == anotherString) ? true
                : (anotherString != null)
                && (anotherString.value.length == value.length)
                && regionMatches(true, 0, anotherString, 0, value.length);
    }

indexOf()

获取某则字符或者字符串在当前字符串中首次出现的索引。技巧:代码的重用。

    // 或者字符ch(Unicode码形式)首次出现的索引
public int indexOf(int ch, int fromIndex) {
        final int max = value.length;
        if (fromIndex < 0) {
            fromIndex = 0;
        } else if (fromIndex >= max) {
            // Note: fromIndex might be near -1>>>1.
            return -1;
        }

        if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
            // handle most cases here (ch is a BMP code point or a
            // negative value (invalid code point))
            final char[] value = this.value;
            for (int i = fromIndex; i < max; i++) {
                if (value[i] == ch) {
                    return i;
                }
            }
            return -1;
        } else {
            return indexOfSupplementary(ch, fromIndex);
        }
    }

    // 代码重用
    public int indexOf(int ch) {
        return indexOf(ch, 0);
    }

/**
     * Code shared by String and StringBuffer to do searches. The
     * source is the character array being searched, and the target
     * is the string being searched for.
     *
     * @param   source       the characters being searched.
     * @param   sourceOffset offset of the source string.
     * @param   sourceCount  count of the source string.
     * @param   target       the characters being searched for.
     * @param   targetOffset offset of the target string.
     * @param   targetCount  count of the target string.
     * @param   fromIndex    the index to begin searching from.
     */
    static int indexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {
        if (fromIndex >= sourceCount) {
            return (targetCount == 0 ? sourceCount : -1);
        }
        if (fromIndex < 0) {
            fromIndex = 0;
        }
        if (targetCount == 0) {
            return fromIndex;
        }

        char first = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);

        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* Look for first character. */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

            /* Found first character, now look at the rest of v2 */
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j]
                        == target[k]; j++, k++);

                if (j == end) {
                    /* Found whole string. */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

    // 字符串首次出现的索引,从fromIndex位置开始搜索
    public int indexOf(String str, int fromIndex) {
        return indexOf(value, 0, value.length,
                str.value, 0, str.value.length, fromIndex);
    }

    // 字符串首次出现的索引,代码重用
    public int indexOf(String str) {
        return indexOf(str, 0);
    }

replace()

替换字符或字符序列,生成新的String对象返回。

public String replace(char oldChar, char newChar) {
        // 如果新旧字符相等则不需要发生替换
        if (oldChar != newChar) {
            int len = value.length;
            int i = -1;
            char[] val = value; /* avoid getfield opcode */

            while (++i < len) {  // 优雅的代码
                if (val[i] == oldChar) {
                    break;
                }
            }
            if (i < len) {
                char buf[] = new char[len];
                for (int j = 0; j < i; j++) {
                    buf[j] = val[j];
                }
                while (i < len) {
                    char c = val[i];
                    buf[i] = (c == oldChar) ? newChar : c;
                    i++;
                }
                return new String(buf, true);
            }
        }
        return this;
    }

    // 替换字符序列
    public String replace(CharSequence target, CharSequence replacement) {
        return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
                this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
    }

substring()

利用构造函数取子串。技巧:索引范围检查和代码重用。

    public String substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        if (endIndex > value.length) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return ((beginIndex == 0) && (endIndex == value.length)) ? this
                : new String(value, beginIndex, subLen);
    }

trim()

去除首尾空格

    public String trim() {
        int len = value.length;
        int st = 0;
        char[] val = value;    /* avoid getfield opcode */

        // 首部空格跳过
        while ((st < len) && (val[st] <= ' ')) {
            st++;
        }
        // 尾部空格跳过
        while ((st < len) && (val[len - 1] <= ' ')) {
            len--;
        }
        // 取子串,代码重用
        return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
    }

getChars()

从字符串读入数据到字符数组,注意,该方法没有进行索引边界检查。

    /**
     * Copy characters from this string into dst starting at dstBegin.
     * This method doesn't perform any range checking.
     */
    void getChars(char dst[], int dstBegin) {
        System.arraycopy(value, 0, dst, dstBegin, value.length);
    }

concat()

连接字符串。技巧:代码重用。

    //Concatenates the specified string to the end of this string.
    public String concat(String str) {
        int otherLen = str.length();
        if (otherLen == 0) {
            return this;
        }
        int len = value.length;
        char buf[] = Arrays.copyOf(value, len + otherLen);
        str.getChars(buf, len);  // 代码重用,从字符串读取数组到字符数组
        return new String(buf, true);   // 构造新的String对象返回
    }

toCharArray()

将字符串转为字符数组。

    public char[] toCharArray() {
        // Cannot use Arrays.copyOf because of class initialization order issues
        char result[] = new char[value.length];
        System.arraycopy(value, 0, result, 0, value.length);
        return result;
    }

valueOf()

由boolean、char、double、int、float、long等基础类型生成String(利用包装类的toString()方法。由字符数组生成String(利用String构造函数)。将object转换为String,比obj+”“和obj.toString()都好,因为从源码中可以看出,valueOf()很好的避免了空指针异常。

    public static String valueOf(char data[]) {
        return new String(data);
    }

    public static String valueOf(int i) {
        return Integer.toString(i);
    }


   public static String valueOf(Object obj) {  
        return (obj == null) ? "null" : obj.toString();  
   }  

    ......

copyValueOf(char[])

类似于构造函数,使用char数组生成String。

    public static String copyValueOf(char data[]) {
        return new String(data);
    }

startWith()、endWith()

    public boolean startsWith(String prefix, int toffset) {
        char ta[] = value;
        int to = toffset;
        char pa[] = prefix.value;
        int po = 0;
        int pc = prefix.value.length;
        // Note: toffset might be near -1>>>1.
        if ((toffset < 0) || (toffset > value.length - pc)) {
            return false;
        }
        while (--pc >= 0) {
            if (ta[to++] != pa[po++]) {
                return false;
            }
        }
        return true;
    }

    // 代码重用
    public boolean startsWith(String prefix) {
        return startsWith(prefix, 0);
    }

    // 代码重用
    public boolean endsWith(String suffix) {
        return startsWith(suffix, value.length - suffix.value.length);
    }

StringBuilder

上面提到String是不可变的对象,任何对String对象的修改最后都会返回一个全新的String对象。如果需要对字符串进行大量的修改时,可以考虑使用StringBuilder,StringBuilder继承自AbstractStringBuilder,而AbstractStringBuilder实现了Appendable接口和CharSequence接口。因此如果对StringBuilder对象进行修改,会将对象中的value[]字符数组进行扩容,之后将添加的新的字符序列添加到value[]的尾部。返回原来的对象。

对字符序列的修改,最主要的是append()和insert(),有很多重载形式。

StringBuilder appendStringBuilder insert

以append(String str)为例,StringBuilder的append直接调用基类AbstractStringBuilder的append(String str)方法:

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

基类AbstractStringBuilder的append(String str)方法首先对value[]数组进行扩容,之后调用String.getChars()方法,将添加的新值拷贝到value[]数组中。

    public AbstractStringBuilder append(String str) {
        if (str == null)
            return appendNull();
        int len = str.length();
        ensureCapacityInternal(count + len);  // value[]数组扩容
        str.getChars(0, len, value, count);  // 将添加的新值拷贝到value[]数组
        count += len;  // 更新字符的数目
        return this;   // 返回同一个StringBuilder对象
    }

String.getChars()方法:主要包括索引边界检查和拷贝数组两个步骤。

    public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
        if (srcBegin < 0) {
            throw new StringIndexOutOfBoundsException(srcBegin);
        }
        if (srcEnd > value.length) {
            throw new StringIndexOutOfBoundsException(srcEnd);
        }
        if (srcBegin > srcEnd) {
            throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
        }
        System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }

注意:StringBuilder的构造函数中指定value[]数组的默认长度为16,即默认能够存储16个字符,如果超过16,则进行自动扩容,由于扩容一页带来一定的开销,如果能够预估最后字符序列的长度,使用重载的构造函数StringBuilder(int capacity)能够有效减小扩容开销,提高效率。另外,StringBuilder不是线程安全的

StringBuffer

StringBuffer是StringBuilder的同步版本,所有的append()和insert()方法都使用synchronized关键字进行了锁定,是线程安全的。由于加锁互斥会带来很大的开销,如果不需要考虑多线程同时修改字符串的情况,推荐使用StringBuilder,既不会产生过多的对象,也不会因为需要加锁而产生很大的开销。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值