java中StringBuffer类的概述及其构造方法
java中StringBuffer的各种功能测试详解(1)
java中StringBuffer的各种功能测试详解(2)
java中StringBuffer类的概述及其构造方法
我们如果对字符串进行拼接操作,每次拼接都会创建一个新的String对象,即耗时又浪费空间,而StringBuffer就可以解决一个问题
- 线程安全(多线程讲解)
- 安全 – 同步 – 数据是安全的
- 不安全 – 不同步 – 效率高一些
- 安全和效率问题是永远困扰我们的问题。
- 安全:医院的网站,银行网站
- 效率:新闻网站,论坛之类的
- StringBuffer:线程安全的可变字符串。
- StringBuffer和String的区别?
- 前者长度和内容可变,后者不可变。
- 如果使用前者做字符串的拼接,不会浪费太多的资源。
-
StringBuffer的构造方法:
public StringBuffer():无参构造方法 public StringBuffer(int capacity):指定容量的字符串缓冲区对象 public StringBuffer(String str):指定字符串内容的字符串缓冲区对象
-
StringBuffer的方法:
public int capacity():返回当前容量。 理论值 public int length():返回长度(字符数)。 实际值
public StringBuffer();
无参构造方法
class test{
public static void main(String[] args){
StringBuffer sb = new StringBuffer();
System.out.println("sb:"+sb);
System.out.println("sb.length:"+sb.length());
System.out.println("sb.capacity:"+sb.capacity());
//如果结果是地址值则说明没有重写
//如果结果结果是空白,啥也没有说明重写了StringBuffer的构造方法
//第一个结果为:sb: 说明重写了构造方法
//第二个结果为:sb.length:0
//第三个结果为:sb.capacity:16,
//16是因为构造一个其中不带字符的字符串缓冲区,其初始容量为 16 个字符。
}
}
public StringBuffer(int capacity)
指定容量的字符串缓冲区对象
class test{
public static void main(String[] args){
StringBuffer sb = new StringBuffer(50);
System.out.println("sb:"+sb);
System.out.println("sb.length:"+sb.length());
System.out.println("sb.capacity:"+sb.capacity());
//第一个输出结果为:sb:
//第二个输出结果为:sb.length:0
//第三个输出结果为:sb.capacity:50;
}
}
public StringBuffer(String str)
指定字符串内容的字符串缓冲区对象
class test{
public static void main(String[] args){
StringBuffer sb = new StringBuffer("hello");
System.out.println("sb:"+sb);
System.out.println("sb.length:"+sb.length());
System.out.println("sb.capacity:"+sb.capacity());
//第一个输出结果为:sb:hello
//第二个输出结果为:sb.length:5
//第三个输出结果为:sb.capacity:21
//21是怎么来的呢?
//通过查看编程得知
/*StringBuffer(String str){
super(str.length()+16);
append(str);
}
*/
}
}