一、字符串缓冲区
1.简介:StringBuffer字符串缓冲区,与字符串String不同的是StringBuffer创建后仍能修改,而String创建之后就不能修改。
String s1="123"; StringBuffer s2=new StringBuffer("123"); System.out.println(s1.hashCode()+" "+s2.hashCode()); s1+="456"; s2.append("456"); System.out.println(s1.hashCode()+" "+s2.hashCode());
48690 118352462
1450575459 118352462输出结果可以说明String对象已经发生变化,StringBuffer没有变化。
其机制是预先申请缓冲区来存储,当存储长度超过缓冲区大小就重新申请新的缓冲区。缓冲区的大小就称作字符串缓冲区的容量,而其中存储的字符个数称为字符串缓冲区的长度。
2.创建
构造方法 | 长度 | 容量 |
public StringBuffer() | 0 | 16 |
public StringBuffer(int capacity) | 0 | capacity |
public StringBuffer(String str) | str.length() | str.length()+16 |
3.操作方法
(1)获得长度 int length().
获得容量 int capacity().
设置容量void ensureCapacity(int minCapacity),若minCapacity小于现有的缓冲区的容量,那么这个方法不起作用,否则就要改变现有的容量,将会是minCapacity和(当前容量)*2+2两个数中较大的一个。
void trimToSize()将容量缩小至与长度相同。
设置长度 void setLength(int newLength),其中参数newLength应该大于等于0,若newLength与现在长度相同,则字符串缓冲区不发生变化;若newLength小于当前长度,则字符串缓冲区只保留前newLength个字符;若newLength大于当前长度,则在后面补上字符'\u0000',其中如果大于容量,需要增加容量,新的容量是newLength与(当前容量)*2+2两个数中较大的一个。
(2)