一、String :
final修饰,不可变,String类的方法都是返回new String。即对String对象的任何改变都不影响到原对象,对字符串的修改操作都会生成新的对象。
二、StringBuffer :
可变, 对字符串的操作的方法都加了synchronized,保证线程安全。
三、StringBuilder :
可变,不保证线程安全,在方法体内需要进行字符串的修改操作,可以new StringBuilder对象,调用StringBuilder对象的append、replace、delete等方法修改字符串。
四、详解String对象不可变
- String对象不可变, 当试图改变String对象时,它实际上是返回了一个新的字符串对象。
//1.string类被final修饰,不可以被继承
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
{
/** The value is used for character storage. */
private final char value[];//2.内部所有成员变量都为私有的,且没有set方法
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
/** Cache the hash code for the string */
private int hash; // Default to 0
....
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length); // deep copy操作
}
...
public char[] toCharArray() {
// Cannot use Arrays.copyOf because of class initialization order issues
char result[] = new char[value.length];
System.arraycopy(value, 0, result, 0, value.length);
return result;//返回对象的copy,而不是对象的引用,不可改变string
}
...
}
- 不可变的优点
1.不可变,天生线程安全,不用使用同步。
2.hashcode确定、提前缓存hashcode,不需要重新计算,处理速度很快,很适合做键值。