StringBuffer类概述及其构造方法
1、StringBuffer类概述
- 如果我们对字符串进行拼接操作,每次拼接,都会构建一个新的String对象,既耗时又浪费空间。而 StringBuffer就可以解决这个问题
- 线程安全的可变字符序列
2、StringBuuffer和String的区别?
前者长度和内容可变,后者不可变
3、构造方法
- public StringBuffer()
- public StringBuffer(int capacity)
- public StringBuffer(String str)
public class StringBufferDemo { public static void main(String[] args) { //public StringBuffer(); StringBuffer buffer1 = new StringBuffer(); System.out.println("buffer1:"+buffer1); System.out.println("buffer1.capacity:"+buffer1.capacity()); System.out.println("buffer1.length:"+buffer1.length()); System.out.println("---------------------------------"); } }
运行结果:
buffer1: buffer1.capacity:16 buffer1.length:0 //没有加入字符
为什么buffer1.capacity为16?
/** * Constructs a string buffer with no characters in it and an * initial capacity of 16 characters. */
public StringBuffer() { super(16); }