不可变类immutable class,就是字面含义,一旦初始化后就不能再被改变的类,比如String
,Integer
等。
如何创建一个不可变类?
1.final
and no setter
2.for nested object / custom object getter
: copy and return
// 1. member variable is nested object: List, Map etc.
public List getPhoneNumbers(){
return new ArrayList<>(phoneNumbers);
}
// 2.member variable is custom object
// custom class implements Cloneable, getter return a clone
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public Address getAddress() throws CloneNotSupportedException {
return (Address) address.clone();
}
3.create copies of collection passed as arg to Constructor, otherwise nothing stops modifying objects outside of the immutable object
A(List<E> list){
this.list = new ArrayList<>(list);
}