目
录
四.String类,StringBuffer类和StringBuilder类的区别
一.StringBuffer类![](https://img-blog.csdnimg.cn/e382290225ef418886f3a423f296a2e0.gif)
1.StringBuffer
我们如果对字符串进行拼接操作,每次拼接,都会构建一个新的String对象,既耗时,又浪费空间.StringBuffer就可以解决这个问题.
StringBuffer是一个字符容器,是线程安全的可变字符序列.
2.StringBuffer的构造方法
- public StringBuffer(): 无参构造方法
- public StringBuffer(int capacity): 指定容量的字符串缓冲区对象
- public StringBuffer(String str): 指定字符串内容的字符串缓冲区对象
public class Test {
public static void main(String[] args) {
// StringBuffer:长度可变的字符容器。
/* StringBuffer() 构造一个其中不带字符的字符串缓冲区,初始容量为 16 个字符。*/
StringBuffer sb = new StringBuffer();
//你可以指定容器容量,例如指定100
StringBuffer stringBuffer = new StringBuffer(100);
//指定字符串内容的字符串缓冲区对象
StringBuffer sb2 = new StringBuffer("abc");
}
}
3.StringBuffer的取容量和长度的方法:
- public int capacity(): 返回当前容量。 理论值
- public int length(): 返回长度(字符数)。 实际值
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
StringBuffer stringBuffer = new StringBuffer(100);
StringBuffer sb2 = new StringBuffer("abc");
//获取容量的方法
int capacity1 = sb.capacity();
System.out.println(capacity1); //16
int capacity2 = stringBuffer.capacity();
System.out.println(capacity2); //100
int capacity3 = sb2.capacity();
System.out.println(capacity3);