1.StringBuffer可以追加字符
public class SyrinBufferDemo1 {
public static void main(String[] args) {
StringBuilder buf = new StringBuilder();
System.out.println(buf.capacity());
buf.append("张三").append("常说")
.append("他爱打游戏");
System.out.println(buf.capadity());
System.out.println(buf);
}
}
//16
//34
//张三常说他爱打游戏
2.StringBuffer的添加和删除功能
*Public StringBuffer append ( String str );
public StringBuffer insert ( int offset , String str );
*public StringBuffer deleteCharAt ( int index );
public StringBuffer delete ( int start ,int end );
public static void main(String[] args) {
StringBuffer sb =new StringBuffer();
sb.append("hehehe");
System.out.println("sb: "+ sb);
sb.insert(6, "hahahaha");
System.out.println(sb);
StringBuffer sb2= new StringBuffer();
sb2.append("hello").append("World");
System.out.println(sb2);
sb2.delete(5, 10);
System.out.println(sb2);
sb2.deleteCharAt(4);
System.out.println(sb2);
}
3.stringBuffer性能比String性能高
public class StringInterview {
public static void main(String[] args) {
String result="";
StringBuffer sbResult=new StringBuffer();
int count=5000;
long startTime=System.currentTimeMillis();
for (int i = 0; i <count; i++)="" {<br=""> result=result+"a";
}
System.out.println("string时间差:"+(System.currentTimeMillis()-startTime));
startTime=System.currentTimeMillis();
for (int i = 0; i <count; i++)="" {<br=""> sbResult.append("a");
}
System.out.println("stringbuffer时间差:"+(System.currentTimeMillis()-startTime));
}
}
//string时间差:32
//stringbuffer时间差:0
4.明天学习内容:StringBuilder类的使用