StringBuilder
- 目的
使用StringBuilder替换一般字符串的拼接是为了防止在拼接的过程中生成大量的中间无用的字符串,而字符串变量一般都是不会被gc掉的拼接的过多的时候会产生大量的内存消耗,
字符串对象的存储的更多内容
- 方法
构造方法
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);
}
构造方法分:
无参,默认初始容量16,
int型参数构造指定默认初始容量,
字符串构造,以字符长度+16作为初始容量,然后调用append方法添加字符串,
字符型序列,和字符串方式相同,获取序列长度+16作为初始容量,调用append方法把内容添加进去。
StringBuilder继承了AbstractStringBuilder,内部量只有两个一个是字符数组values[],另一个是int 型的count用来指定占用字节
-
常用方法
append():
stringBuilder中有大量的append方法,基本使用的就是字符串,和StringBuilder对象本身调用append,其余的还支持字符数组,字符串数组,和基本数据类型boolean,float,int,char,long,double。appendCodePoint
(int codePoint)就是将ascii码输入,追加为对应ascii码的值
在append的时候如果sb对象的value容量不能满足即将拼接后的字符容量,就会进行扩容。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);
}
扩容的时候使用的是数组复制,所以在这里使用的时候尽量预估要拼接的最大长度避免扩容,提升效率。
insert:
insert(offset,content),offset为插入的索引位置,插入的内容会占据此位置。
可以在指定的位置插入字符串。插入的是字符数组的时候,会有要插入字符数组的起始位置offset,和长度len的参数。
delete:
delete(int start,int end)方法,删除从start索引出开始至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;
就是把end后的内容复制到原values数组的start位置起相当于把后面的内容剪切然后从start位置向后开始覆盖。deleteCharAt(index)等同于delete(index,index+1)
replace:
replace(start,end,str)指定索引开始到截止索引之前的所有内容都以指定内容替换,还是使用system.arraycopy();
indexOf:
indexOf(‘string’),获取指定字符串在builder内容中开始出现的索引,多次出现取第一次出现的索引值,找不到返回-1
indexOf(“string”,int formindex):从指定索引在buildler的内容中获取索引,搜索的位置包含此位置。
lastIndexOf(“string”),lastIndexOf(“string”,fromindex),基本类似但是从右侧开始匹配。底层使用String的indeof方法实现
reverse:
reverse(),将内容镜像反转
toString:
return new String(value, 0, count);
用value数组创建内容长度的字符串。
writeObject 和 readObject:
读写对象序列化