1、可變字符串(StringBuffer)概述
①StringBuffer:字符串緩衝區,是線程安全的,只是效率稍微慢一點。
②StringBuffer和String的比較:String一旦被創建後,值不能改變,如果參與了操作,引用發生了變化,不是在原有的字符串上操作,而是新產生了一個字符串;StringBuffer是在原有字符串上操作,不會新產生字符串。
public class StringBufferDemo {
public static void main(String[] args) {
//創建可變字符串
StringBuffer sb = new StringBuffer();
//把可變字符串做追加
StringBuffer sb1 = sb.append(true);
System.out.println(sb1);
//判斷追加後的字符串的地址
System.out.println(sb == sb1);
String str = "abc";
//字符串加上任何類型返回的都是字符串
String str1 = str + true;
//System.out.println(str1);
//String字符串的地址比較
System.out.println(str == str1);
}
}
2、StringBuffer構造器
public class StringBufferDemo1 {
public static void main(String[] args) {
//創建可變字符串,開闢了一個默認是16個字符的空間
StringBuffer sb = new StringBuffer();
System.out.println("可變字符串的長度:"+sb.length()+" 容量:"+sb.capacity());
sb.append("hellohellohellohello");
System.out.println("可變字符串的長度:"+sb.length()+" 容量:"+sb.capacity());
//創建一個10個容量的字符串
StringBuffer sb1 = new StringBuffer(10);
sb1.append("hellohellohellohello");
System.out.println("可變字符串的長度:"+sb1.length()+" 容量:"+sb1.capacity());
//創建一個帶有字符串的參數的可變字符串對象
StringBuffer sb2 = new StringBuffer("hellohellohellohello");
System.out.println("可變字符串的長度:"+sb2.length()+" 容量:"+sb2.capacity());
}
}
3、追加方法
public class StringBufferDemo2 {
public static void main(String[] args) {
//創建可變字符串,開闢了一個默認是16個字符的空間
StringBuffer sb = new StringBuffer();
sb.append(true)
.append('a')
.append(new char[]{'a','g','g'})
.append("hello")
.append(100d)
.append(14.5f)
.append(13)
.append(900l);
System.out.println(sb);
}
}
4、小結
①java.lang下的類不需要引用,可直接使用;
②字符串加上任何類型返回的都是字符串;
③StringBuffer是線程安全的,只是效率稍低;
④StringBuffer的追加方法append()是在原基礎上相加的;
⑤StringBuffer默認構造器創建了一個默認的16個字符的空間。