string和stringbuffer和stringbuilder的区别:
String:不可变字符序列;底层使用char[]存储;
StringBuffer:可变字符序列;线程安全的,效率低;底层使用char[]存储;
StringBuilder:可变字符序列;线程不安全的,效率高;底层使用char[]存储;
在单线程情况下执行效率大部分情况为:StringBuilder>StringBuffer>String
– StringBuilder与StringBuffer有公共父类AbstractStringBuilder(抽象类)。
-
StringBuffer()
– public StringBuffer() ------>构造一个没有字符的字符串缓冲区,并构造了16个字符的初始容量。
– public StringBuffer(int capacity) ------>构造一个没有字符的字符串缓冲区,并构造指定的初始容量。
参数 :capacity -初始容量。
异常 :NegativeArraySizeException -如果 capacity参数小于 0。
– public StringBuffer(String str) ------>构造一个初始化为指定字符串内容的字符串缓冲区。字符串缓冲区的初始容量是 16加字符串的长度。
参数 :str -缓冲区的初始内容。 -
StringBuffer()底层数组扩容问题:如果要添加的数据底层数组放不下了,那就需要扩容底层的数组
– 默认情况下,扩容为原来容量的 2倍+2 ,同时将原有数组中的元素复制到新的数组中
private int newCapacity(int minCapacity) {
// overflow-conscious code
int newCapacity = (value.length << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
public class StringBufferBuilder {
@Test
public void test1(){
//StringBuffer append(xxx): 提供很多的字符串方法,用于字符串拼接
StringBuffer sb1 = new StringBuffer("java");
sb1.append(1);
sb1.append("abc");
System.out.println(sb1);//java1abc
//StringBuffer delete(int Start,int end) : 删除指定位置的内容
sb1.delete(4, 6);
System.out.println(sb1);//javabc
//StringBuffer replace(int start,int end,String str) : 把[start,end)位置替换为str
sb1.replace(4,6,"xy");
System.out.println(sb1);//javaxy
//StringBuffer insert(int offset,xxx) : 在指定位置插入xxx
sb1.insert(4,true);
System.out.println(sb1);//javatruexy
System.out.println(sb1.length());
//StringBuffer reverse() : 把当前字符序列逆转
sb1.reverse();
System.out.println(sb1);//yxeurtavaj
//public String subString(int start,int end) : 返回一个从start开始到end索引结束的左闭右开的子字符串
String str = sb1.substring(6, 10);
System.out.println(str);//avaj
//public void setCharAt(int index,char ch) : 将指定索引位置的字符更改为ch
sb1.setCharAt(0,'z');
System.out.println(sb1);
//public char charAt(int n) : 返回指定索引位置上的字符
char charAt = sb1.charAt(1);
System.out.println(charAt);
//public int indexOf(String str) : 返回字符串str在指定的当前StringBuffer当中首次出现的位置
int indexOf = sb1.indexOf("ta");
System.out.println(indexOf);//5
}
}