字符串緩衝類:因爲String是不可變的,在須要頻繁改變字符對象的狀況下,須要使用可變的字符串緩衝區類。css
特色:java
StringBuffer sb = new StringBuffer("hcx");
sb.append(true);
sb.append('a');
sb.append(97).append(98).append(new char[]{'b','c'}); // 鏈式編程
System.out.println(sb.toString());// 輸出緩衝區的中文本數據 hcxtruea9798bc
sb = new StringBuffer("hcx");
sb.insert( 2, "java" );
System.out.println( sb.toString() );//hcjavax
複製代碼
StringBuffer sb1 = new StringBuffer("hcxx");
System.out.println(sb1.indexOf("x"));//2
System.out.println(sb1.lastIndexOf("x"));//3
複製代碼
StringBuffer sb2 = new StringBuffer("helloworld");
System.out.println(sb2.replace(2, 6, "java"));//替換掉 llow 包頭不包尾 hejavaorld
sb2.setCharAt(8, 'A');//l-->A
System.out.println(sb2);//hejavaorAd
StringBuffer sb4 = new StringBuffer("helloworld");
System.out.println(sb4.reverse());//dlrowolleh
複製代碼
StringBuffer sb3 = new StringBuffer("helloworld");
System.out.println(sb3.delete(2, 4));//heoworld
System.out.println(sb3.deleteCharAt(2));//heworld
複製代碼
使用Stringbuffer無 參的構造函數建立一個對象時,默認的初始容量是多少? 若是長度不夠使用了,自動增加多少倍?編程
StringBuffer底層是依賴了一個字符數組才能存儲字符數據的,該字符串數組默認的初始容量是16, 若是字符數組的長度不夠使用時,自動增加1倍。數組
StringBuffer 與 StringBuilder的相同處與不一樣處:安全
相同點:
1. 兩個類都是字符串緩衝類。
2. 兩個類的方法都是一致的。
不一樣點:
1. StringBuffer是線程安全的,操做效率低 ,StringBuilder是線程非安全的,操做效率高。
2. StringBuffer是jdk1.0出現 的,StringBuilder 是jdk1.5的時候出現的。
複製代碼
推薦使用: StringBuilder,由於操做效率高。app