StingBuilder
线程不安全的可变字符序列
1)构造方法
StringBuilder():以默认容量创建空的字符串缓冲区对象
StringBuilder(int capacity):以指定容量创建空StringBuilder对象
StringBuilder(String str):以指定字符串创建StringBuilder对象
2、String、StringBuffer、StringBuilder三者的对比
String:不可变的字符序列;底层使用char[]存储
StringBuffer:可变的字符序列;线程安全的,效率低;底层使用char[]存储
StringBuilder:可变的字符序列;jdk5.0新增的,线程不安全的,效率高;底层使用char[]存储
StringBuilder w=new StringBuilder();
//w=null;
System.out.println(w); //空字符串
System.out.println(w.length()); //0
System.out.println(w.capacity()); //容量为16
System.out.println("======================");
//构造一个指定容量的StringBuilder
StringBuilder w2=new StringBuilder(100);
System.out.println(w2);
System.out.println(w2.length()); //0
System.out.println(w2.capacity()); //100
StringBuilder w3=new StringBuilder("abc");
System.out.println(w3);
System.out.println(w3.length()); //3
System.out.println(w3.capacity()); //容量为19 "ab
System.out.println("==========================");
StringBuilder w4=new StringBuilder();
w4.append("abcdeqweqwieqwiorhwqruhqwwepqw5646454868446456eqwejiqwioeqwihehqwrweqweqweqweqwdeqwewuioj");
System.out.println(w4);
System.out.println(w4.length()); //89
System.out.println(w4.capacity()); //89
StringBuilder w5=new StringBuilder("abcdeqweqwieqwiorhwqruh546456pqw56464548684eqwejiqwioeqwihehqwrweqweqweqweqwdeqwewuioj");
System.out.println(w5);
System.out.println(w5.length()); //86
System.out.println(w5.capacity()); //102
StringBuilder w=new StringBuilder();
//添加 (链式编程)调用方法后返回一个对象继续调用
w.append("abc").append(false).append(100).append("ab".getBytes());//没有byte的toString方法返回对象的地址值信息
/*默认扩容*/
StringBuilder s1=new StringBuilder();
s1.append("eqweqwieqwiorhwqruh5464");
System.out.println(s1.length()); //23
System.out.println(s1.capacity()); //34
s1.append("eqweqwieqwiorhwqruh5464");
System.out.println(s1.length()); //46
System.out.println(s1.capacity()); //70 第二次扩容
StringBuilder的默认容器为16。
扩容问题:如果要添加的数据底层数组装不下,那就需要扩容底层的数组。 默认情况下,扩容为原来容量的2倍 + 2,同时将原数组中的元素复制到新的数组中。
建议:StringBuffer(int capacity) 或 StringBuilder(int capacity)
如果给StringBuilder赋值为空,不会出现异常,但是length()和capacity会出现空指针异常,所以StringBuilder不能赋空值。
String str = new String(); //char[] value = new char[0];
String str1 = new String("abc"); //char[] value = new char[]{'a','b','c'};
StringBuffer sb1 = new StringBuffer(); //char[] value = new char[16];底层创建了一个长度是16的数组。
System.out.println(sb1.length());
sb1.append('a'); //value[0] = 'a';
sb1.append('b'); //value[1] = 'b';
StringBuffer sb2 = new StringBuffer("abc"); //char[] value = new char["abc".length() + 16];