StringBuider 和StringBUffer 区别

我们从2方面考虑:

共同点:

StringBuider 和StringBUffer  都是String的特殊的线性数据结构。

源码上:

 StringBuffer :

1:定义
public final class StringBuffer extends AbstractStringBuilder implements java.io.Serializable, CharSequence
2:属性

 static final long serialVersionUID = 3388685877147921107L;
3:构造函数

(1)构造一个其中不带字符的字符串缓冲区,初始容量为 16 个字符。

 public StringBuffer() {
        super(16);
    }
继承父类的AbstractStringBuilder的构造函数

AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }
(2)构造一个不带字符,但具有指定初始容量的字符串缓冲区

public StringBuffer(int capacity) {
        super(capacity);
    }
(3)构造一个字符串缓冲区,并将其内容初始化为指定的字符串内容。该字符串的初始容量为 16 加上字符串参数的长度

public StringBuffer(String str) {
//这个执行父类的带参构造函数AbstractStringBuilder(int capacity) 
        super(str.length() + 16);
        append(str);
    }
append 是用 synchronized 修饰的,所以是线程安全的
public synchronized StringBuffer append(String str) {  
        //执行父类的append(str)  
        super.append(str);  
        return this;  

父类 AbstractStringBuilder 的 append 方法

 public AbstractStringBuilder append(String str) {
        if (str == null) str = "null";
        int len = str.length();
        ensureCapacityInternal(count + len);//扩大容量      
        str.getChars(0, len, value, count);
        count += len;
        return this;
    }
//扩大容量

private void ensureCapacityInternal(int minimumCapacity) {  
        // overflow-conscious code:判断是否需要扩容,也就是说原来的capacity是否足够大  
        if (minimumCapacity - value.length > 0) //20-19=1,1>0  
            expandCapacity(minimumCapacity);  
    }  
void expandCapacity(int minimumCapacity) {
        //新容量  原始容量 * 2 + 2
        int newCapacity = value.length * 2 + 2;
        if (newCapacity - minimumCapacity < 0)     //扩容后的容量-字符串实际长度<0(就是说如果扩容后还装不下),
            newCapacity = minimumCapacity;    //则使用字符串实际长度作为StringBuffer的capacity 
        if (newCapacity < 0) {//扩容后的容量超过integer的最大值
           if (minimumCapacity < 0) // overflow //最终容量超过integer的最大值
               throw new OutOfMemoryError();
            newCapacity = Integer.MAX_VALUE;
        }
        //将旧的值剪切到新的字符数组。
        value = Arrays.copyOf(value, newCapacity);

StringBuilder :

源码分析
定义
public final class StringBuilder
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{
    ...
}
1
2
3
4
5
6
StringBuilder类被 final 所修饰,因此不能被继承。

StringBuilder类继承于 AbstractStringBuilder类。实际上,AbstractStringBuilder类具体实现了可变字符序列的一系列操作,比如:append()、insert()、delete()、replace()、charAt()方法等。值得一提的是,StringBuffer也是继承于AbstractStringBuilder类。

StringBuilder类实现了2个接口:

Serializable 序列化接口,表示对象可以被序列化。
CharSequence 字符序列接口,提供了几个对字符序列进行只读访问的方法,比如:length()、charAt()、subSequence()、toString()方法等。
主要变量
// AbstractStringBuilder.java

char[] value;

int count;
1
2
3
4
5
这两个变量是定义在AbstractStringBuilder类中的。其中:

value 用来存储字符序列中的字符。value是一个动态的数组,当存储容量不足时,会对它进行扩容。
count 表示value数组中已存储的字符数。
构造方法
public StringBuilder() {
    super(16);
}

public StringBuilder(int capacity) {
    super(capacity);
}

public StringBuilder(String str) {
    super(str.length() + 16);
    append(str);
}

public StringBuilder(CharSequence seq) {
    this(seq.length() + 16);
    append(seq);
}

// AbstractStringBuilder.java
AbstractStringBuilder(int capacity) {
    value = new char[capacity];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
StringBuilder类提供了4个构造方法。构造方法主要完成了对value数组的初始化。其中:

默认构造方法设置了value数组的初始容量为16。
第2个构造方法设置了value数组的初始容量为指定的大小。
第3个构造方法接受一个String对象作为参数,设置了value数组的初始容量为String对象的长度+16,并把String对象中的字符添加到value数组中。
第4个构造方法接受一个CharSequence对象作为参数,设置了value数组的初始容量为CharSequence对象的长度+16,并把CharSequence对象中的字符添加到value数组中。
append()方法
@Override
public StringBuilder append(boolean b) {
    super.append(b);
    return this;
}

// AbstractStringBuilder.java
public AbstractStringBuilder append(boolean b) {
    if (b) {
        ensureCapacityInternal(count + 4);
        value[count++] = 't';
        value[count++] = 'r';
        value[count++] = 'u';
        value[count++] = 'e';
    } else {
        ensureCapacityInternal(count + 5);
        value[count++] = 'f';
        value[count++] = 'a';
        value[count++] = 'l';
        value[count++] = 's';
        value[count++] = 'e';
    }
    return this;
}    

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

// AbstractStringBuilder.java
public AbstractStringBuilder append(String str) {
    if (str == null)
        return appendNull();
    int len = str.length();
    ensureCapacityInternal(count + len);
    str.getChars(0, len, value, count);
    count += len;
    return this;
}    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
append()方法将指定参数类型的字符串表示形式追加到字符序列的末尾。StringBuilder类提供了一系列的append()方法,它可以接受boolean、char、char[]、CharSequence、double、float、int、long、Object、String、StringBuffer这些类型的参数。这些方法最终都调用了父类AbstractStringBuilder类中对应的方法。最后,append()方法返回了StringBuilder对象自身,以便用户可以链式调用StringBuilder类中的方法。

AbstractStringBuilder类的各个append()方法大同小异。append()方法在追加字符到value数组中之前都会调用ensureCapacityInternal()方法来确保value数组有足够的容量,然后才把字符追加到value数组中。

private void ensureCapacityInternal(int minimumCapacity) {
    // overflow-conscious code
    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);
}

// Arrays.java
public static char[] copyOf(char[] original, int newLength) {
    char[] copy = new char[newLength];
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}

ensureCapacityInternal()方法判断value数组的容量是否足够,如果不够,那么调用expandCapacity()方法进行扩容。

expandCapacity()方法默认情况下将数组容量扩大到原数组容量的2倍+2。数组的容量最大只能扩容到Integer.MAX_VALUE。最后,调用Arrays类的copyOf()静态方法来创建一个新数组和拷贝原数据到新数组,并将value指向新数组。

delete()方法
@Override
public StringBuilder delete(int start, int end) {
    super.delete(start, end);
    return this;
}

// AbstractStringBuilder.java
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;
}    

delete()方法删除指定位置的字符。删除的字符从指定的start位置开始,直到end-1位置。delete()方法也调用了父类AbstractStringBuilder类中对应的方法。

delete()方法首先检查参数的合法性。当end大于value数组中已存储的字符数count时,end取count值。最后,当需要删除的字符数大于1的时候,调用System类的arraycopy()静态方法进行数组拷贝完成删除字符的操作,并更新count的值。

replace()方法
@Override
public StringBuilder replace(int start, int end, String str) {
    super.replace(start, end, str);
    return this;
}

// AbstractStringBuilder.java
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.getChars(value, start);
    count = newCount;
    return this;
}

// String.java
void getChars(char dst[], int dstBegin) {
    System.arraycopy(value, 0, dst, dstBegin, value.length);
}

replace()方法将指定位置的字符替换成指定字符串中的字符。替换的字符从指定的start位置开始,直到end-1位置。replace()方法也调用了父类AbstractStringBuilder类中对应的方法。

replace()方法首先检查参数的合法性。当end大于value数组中已存储的字符数count时,end取count值。然后调用ensureCapacityInternal()方法确保value数组有足够的容量。接着调用System类的arraycopy()静态方法进行数组拷贝,主要的作用是从start位置开始空出替换的字符串长度len大小的位置。最后,调用String类的getChars()方法将替换的字符串中的字符拷贝到value数组中。这样就完成了替换字符的操作。

charAt()方法
// AbstractStringBuilder.java
@Override
public char charAt(int index) {
    if ((index < 0) || (index >= count))
        throw new StringIndexOutOfBoundsException(index);
    return value[index];
}

charAt()方法返回指定索引处的char字符。索引的范围从0到count-1。charAt()方法定义在父类AbstractStringBuilder类中。

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

toString()方法返回一个表示该字符序列的字符串。

总结
StringBuilder类使用了一个char数组来存储字符。该数组是一个动态的数组,当存储容量不足时,会对它进行扩容。
StringBuilder对象是一个可变的字符序列。
StringBuilder类是非线程安全的。

StringBuffer类是线程安全的。

  • StringBuffer类使用了一个char数组来存储字符。该数组是一个动态的数组,当存储容量不足时,会对它进行扩容。
  • StringBuffer对象是一个可变的字符序列。
  • StringBuffer类是线程安全的。

参考资料:

java StringBuffer和StringBuilder_SHAN_9W的博客-CSDN博客_javastringbuffer和stringbuilder

StringBuffer 源码_wqqqianqian的博客-CSDN博客_stringbuffer源码

Java | StringBuilder源码分析_chongyucaiyan的博客-CSDN博客_stringbuilder源码分析

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执于代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值