JDK源码之String,StringBuffer,StringBuilder分析

前言

最近公司招聘Java开发人员,面试时会问一些jdk源码相关的问题,如String相关,但很少有答得全面的,今天总结一下,供学习参考

String,StringBuffer,StringBuilder之间的对比:
特性StringStringBufferStringBuilder
可继承性类由final修饰,不能被继承类由final修饰,不能被继承类由final修饰,不能被继承
底层结构由final修饰的char[]可变的char[]可变的char[]
默认长度1616
扩容机制父类中的方法expandCapacity进行扩容实现, 检测到数组长度不够容纳新元素时,进行扩容,新容量大小=value.length * 2 + 2, 若还不够, 则直接扩到需要的大小同StringBuffer一样
实现的接口Serializable, Comparable, CharSequenceSerializable, CharSequenceSerializable, CharSequence
继承的类AbstractStringBuilder, 很多操作都是调用父类中的方法AbstractStringBuilder, 很多操作都是调用父类中的方法
线程安全性线程安全,内部方法实现都由synchronized修饰线程非安全
适用场景要操作少量的数据,较少更改多线程环境下操作大量字符数据单线程环境下操作大量字符数据
hashCode的实现重写了hashCode未重写,调用Object的native方法hashCode同StringBuffer一样
equals的实现重写了equals方法,比较的值是否相等未重写,调用Object的方法equals,使用==比较,比较的是内存地址是否相等同StringBuffer一样
序列化的实现内部定义了writeObject和readObject, 序列化及反序列化时会调用应对的方法, 主要实现value及count的写入同StringBuffer一样
总结:
  • 三者的继承结构(这里忽略了Serializable)
    在这里插入图片描述

  • StringBuffer与StringBuilder两者之间的主要区别
    (1)线程安全性,StringBuffer是线程安全的,而StringBuilder是线程非安全的,也因此在速度上, StringBuilder优于StringBuffer
    (2)还有一点,StringBuffer内部有针对toString()的cache, 字段名toStringCache,StringBuffer每次操作都会将toStringCache设置为null

  • 性能,速度
    使用StringBuffer与StringBuilder时,注意初始化长度的设定,避免出现频繁扩容而导致的资源浪费
    大多数情况下:StringBuilder > StringBuffer > String
    单字符串操作时, String最佳, 如下:

String s1 = "abc";
StringBuilder s2 = new StringBuilder().append("abc");
  • 使用哪一个
    有大量字符串拼接或修改时, 单线程环境下用StringBuilder, 多线程环境下用StringBuffer, 若使用String进行大量字符拼接操作, 则会产生大量垃圾对象,浪费系统资源并且会影响系统性能
    不涉及字符拼接以及更改时,直接使用String最佳
源码赏析:
  • StringBuffer与StringBuilder序列化的实现
StringBuffer的实现:
/**
 * readObject is called to restore the state of the StringBuffer from
 * a stream.
 */
private synchronized void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException {
    java.io.ObjectOutputStream.PutField fields = s.putFields();
    fields.put("value", value);
    fields.put("count", count);
    fields.put("shared", false);
    s.writeFields();
}

/**
 * readObject is called to restore the state of the StringBuffer from
 * a stream.
 */
private void readObject(java.io.ObjectInputStream s)
    throws java.io.IOException, ClassNotFoundException {
    java.io.ObjectInputStream.GetField fields = s.readFields();
    value = (char[])fields.get("value", null);
    count = fields.get("count", 0);
}
    
StringBuilder的实现:
/**
 * Save the state of the {@code StringBuilder} instance to a stream
 * (that is, serialize it).
 *
 * @serialData the number of characters currently stored in the string
 *             builder ({@code int}), followed by the characters in the
 *             string builder ({@code char[]}).   The length of the
 *             {@code char} array may be greater than the number of
 *             characters currently stored in the string builder, in which
 *             case extra characters are ignored.
 */
private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException {
    s.defaultWriteObject();
    s.writeInt(count);
    s.writeObject(value);
}

/**
 * readObject is called to restore the state of the StringBuffer from
 * a stream.
 */
private void readObject(java.io.ObjectInputStream s)
    throws java.io.IOException, ClassNotFoundException {
    s.defaultReadObject();
    count = s.readInt();
    value = (char[]) s.readObject();
}
  • StringBuffer与StringBuilder的扩容检测及实现
AbstractStringBuilder类中的方法
//扩容检测
private void ensureCapacityInternal(int minimumCapacity) {
	//数组长度不够容纳新元素时,进行扩容
    if (minimumCapacity - value.length > 0)
        expandCapacity(minimumCapacity);
}

//扩容实现
void expandCapacity(int minimumCapacity) {
    int newCapacity = value.length * 2 + 2;
    if (newCapacity - minimumCapacity < 0)
        newCapacity = minimumCapacity;
    if (newCapacity < 0) {
        if (minimumCapacity < 0) // overflow
            throw new OutOfMemoryError();
        newCapacity = Integer.MAX_VALUE;
    }
    //开辟一个新数组, 并且原数组的元素复制过去
    value = Arrays.copyOf(value, newCapacity);
}
  • String类重写的hashCode方法实现
public int hashCode() {
    int h = hash;
    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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值