定义
不可变类指当类被实例化后,该类的成员变量均不可被改变。如JDK内部自带的很多不可变类:Interger、Long和String等。
优点
1.线程安全 2.易于构造、使用和测试 3.可以被自由地共享
缺点
对于每一个不同的值都需要对应一个单独的对象
类设计原则
1.class要用final修饰,保证类不能被继承;
2.成员变量需要用private String来修饰,保证成员变量均为私有变量;
3.类中不允许提供setter方法,保证成员变量不会被改变;
4.成员变量的getter方法中返回该对象的复制对象,保证原对象的引用不被改变;
String对象的不可变性
string对象在内存创建后就不可改变,不可变对象的创建一般满足以上4个原则,我们看看String代码是如何实现的。
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
{
/** The value is used for character storage. */
private final char value[];
/** 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;
}
...
}
如上代码所示,可以观察到以下设计细节:
- String类被final修饰,不可继承
- string内部所有成员都设置为私有变量
- 不存在value的setter
- 并将value和offset设置为final。
- 获取value时不是直接返回对象引用,而是返回对象的copy.
这都符合上面总结的不变类型的特性,也保证了String类型是不可变的类。