Stringbuffer和Stringbuider的基础理解
1.Stringbuffer
1.1 Stringbuffer是线程安全的,对应的Stringbuider不安全
1.2Stringbuffer和Stringbuider都是用来追加字符的,不像直接
追加字符串,两者提供一个缓冲区,不会大大量的浪费对象,
不用的字符串就会被回收,不会像一般的组装字符串,新的对
象不会改变,永不回收,建议先给初始化一个合适的大小,对其优化,另外就是初始化的时候先给的是默认的16byte的大小的字符串缓存区的对象,
2.对Stringbuffer的源码的基础分析,—新手需要掌握的程度
1.号代码片段
public class StringBufferTest {
public static void main(String[] args) {
StringBuffer stringBuffer =new StringBuffer();
stringBuffer.append("a");
}
}
2号片段
StringBuffer stringBuffer =new StringBuffer();
stringBuffer.append("a");
3.对2号片段的分析
1.第一步,这是个对象的定义,首先有构造方法的执行,我们进去看看对象
构造方法的执行
构造方法:
public StringBuffer() {
super(16);
}
这个构造方法默认执行了父类的构造方法,那么他的父类是哪个呢?
父类的构造方法:
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
16传给了这个构造方法,new后面是一个char类型的数组,大小就是传进来的16,不用看,这个value就是同类型的数组了
----------------------------------构造方法分析结束:
2.接下来分析后面的append();方法了
就是下面的方法:
stringBuffer.append("a");
首先我们看到传进去了一个a的字符串,append是可以传进去任何的东西的,都给追加成一个新的字符串,这是怎么实现的呢,我们仍然看一下源码
append();源码:
public synchronized StringBuffer append(String str) {
toStringCache = null;
super.append(str);
return this;
}
我们看到了这个东西,我们看到形参的类型是一个字符串,和我们传进来的是一样的,,其次后面括号里面有三个方法
首先我们看第一个就是
toStringCache = null;
我们进去看一下源码:
* A cache of the last value returned by toString. Cleared
* whenever the StringBuffer is modified.
*/
private transient char[] toStringCache;
注释翻译:上一个来自toString方法的缓存区,只要Stringbuffer 这个对象修改就会被清除,
什么意思呢???
.
.
.
-------------就是我们定义了一个数组,这个数组充当的是一个缓存的功能,,相对比字符串数组的不可改变,这里提到了缓存的功能。是可以改变的。首先这个字符串数组的初始值是null。是空的
接着看代码
super.append(str);
调用了父类的append方法,把我们的传进去的字符串给传入了进去
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;
}
一下子出来这么多东西,慢慢看
if (str == null)
return appendNull();
我们看一下这个appendNull();方法是什么。
private AbstractStringBuilder appendNull() {
int c = count;
ensureCapacityInternal(c + 4);
final char[] value = this.value;
value[c++] = 'n';
value[c++] = 'u';
value[c++] = 'l';
value[c++] = 'l';
count = c;
return this;
}
首先我们明白这个count是什么
* The count is the number of characters used.
*/
int count;
注释翻译:就是这个count存储了,已经存在的字符串的字符的个数,
怎么存的就先不用管了,肯定通过方法给传递了,我们知道是什么就行了
en开头的方法就先不讲了,大意就是给数组加4个byte的空间,后面代码的意思把我们传入的数字如果是null的时候,就给添加上去
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;
}
我们看这个代码: ensureCapacityInternal(count + len);
就是前面说过了,传入的是null 就把null加上去,不是的话接着执行,就把我们传入的新的字符的长度给加上去