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个字符的空间。