String类,内部实现使用到final关键字,所以每次修改或者赋值String类型变量时,其都会分配新的地址。
public static void main(String[] args) {
String str = "hello";
System.out.println(str.hashCode());
str +="world";
System.out.println(str.hashCode());
StringBuffer buffer = new StringBuffer();
buffer.append("hello");
System.out.println(buffer.hashCode());
buffer.append("world");
System.out.println(buffer.hashCode());
StringBuilder builder = new StringBuilder();
builder.append("hello");
System.out.println(builder.hashCode());
builder.append("world");
System.out.println(builder.hashCode());
}
/*
运行结果:
99162322
-1524582912
1163157884
1163157884
1956725890
1956725890
*/
StringBuilder与StringBuffer都是在原对象上进行的操作
StringBuffer线程安全,方法由synchronized修饰,而StringBuilder线程不安全
在性能上:
StringBuilder > StringBuffer > String