共同点
他们都是可变的,在每次进行修改操作时,都不会产生新的对象,所以在进行修改的时候,尽量使用这两种类型的字符串
不同点
StringBuffer在单线程中效率高
StringBuilder用于多线程确保安全性
测试代码
public class test {
public static void main(String[] args) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("a");
System.out.println(stringBuilder.hashCode());
stringBuilder.append("b");
System.out.println(stringBuilder.hashCode());
stringBuilder.append("c");
System.out.println(stringBuilder.hashCode());
System.out.println(stringBuilder);
String string = new String();
string += "1";
System.out.println(string.hashCode());
string += "2";
System.out.println(string.hashCode());
string += "3";
System.out.println(string.hashCode());
System.out.println(string);
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("a");
System.out.println(stringBuffer.hashCode());
stringBuffer.append("b");
System.out.println(stringBuffer.hashCode());
stringBuffer.append("c");
System.out.println(stringBuffer.hashCode());
}
}