📅  最后修改于: 2020-09-25 14:56:44             🧑  作者: Mango
String和StringBuffer之间有许多区别。下面列出了String和StringBuffer之间的差异:
No. | String | StringBuffer |
---|---|---|
1) | String class is immutable. | StringBuffer class is mutable. |
2) | String is slow and consumes more memory when you concat too many strings because every time it creates new instance. | StringBuffer is fast and consumes less memory when you cancat strings. |
3) | String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. | StringBuffer class doesn’t override the equals() method of Object class. |
public class ConcatTest{
public static String concatWithString() {
String t = "Java";
for (int i=0; i<10000; i++){
t = t + "Tpoint";
}
return t;
}
public static String concatWithStringBuffer(){
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("Tpoint");
}
return sb.toString();
}
public static void main(String[] args){
long startTime = System.currentTimeMillis();
concatWithString();
System.out.println("Time taken by Concating with String: "+(System.currentTimeMillis()-startTime)+"ms");
startTime = System.currentTimeMillis();
concatWithStringBuffer();
System.out.println("Time taken by Concating with StringBuffer: "+(System.currentTimeMillis()-startTime)+"ms");
}
}
正如您在下面给出的程序中看到的那样,当您连接字符串时,String返回新的哈希码值,但是StringBuffer返回相同的值。
public class InstanceTest{
public static void main(String args[]){
System.out.println("Hashcode test of String:");
String str="java";
System.out.println(str.hashCode());
str=str+"tpoint";
System.out.println(str.hashCode());
System.out.println("Hashcode test of StringBuffer:");
StringBuffer sb=new StringBuffer("java");
System.out.println(sb.hashCode());
sb.append("tpoint");
System.out.println(sb.hashCode());
}
}