让final融入你的程序习惯。
final常量:
final变量:
final参数:
final集合:Collections.unmodifiableSet(temp);
final实例变量:
final类:
final方法:
使用final完成条件编译:
Immutable对象应注意的问题:
是private 实例变量不代表别人不可改变它的:
1. private Mutable变量:得到Mutable变量引用便可改变其中的内容。
2.使使用用反射可以突破引用变量或方法的访问限制:Class java.lang.reflect.AccessibleObject。
因此真正的不可变对象应注意:
对传入的对象进行拷贝:setPoint(Point p){this.point = new Point(p)};
对返回的对象进行拷贝:getPoint(){return new Point(this.point);}
注意利用反射突破访问限制直接修改属性:使用final来避免。private final 。。。这样只要值定下来就真正不可改变了。
由于不可变对象的固有特性:对于大对象应慎重考虑是否应该不可变的:每次返回都需要进行大对象的拷贝,十分影响性能。String--》StringBuffer就是一个例子(改变对象时应该慎重考虑使用"+"运算符)。
以下是不可变集合的一种实现方法:JDK源码中有
public static Collection unmodifiableCollection(Collection c) {
return new UnmodifiableCollection(c);
}
static class UnmodifiableCollection implements Collection, Serializable {
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 1820017752578914078L;
Collection c;
UnmodifiableCollection(Collection c) {
if (c==null)
throw new NullPointerException( );
this.c = c;
}
public int size( ) {return c.size( );}
public boolean isEmpty( ) {return c.isEmpty( );}
public boolean contains(Object o) {return c.contains(o);}
public Object[] toArray( ) {return c.toArray( );}
public Object[] toArray(Object[] a) {return c.toArray(a);}
public String toString( ) {return c.toString( );}
public Iterator iterator( ) {
return new Iterator( ) {
Iterator i = c.iterator( );
public boolean hasNext( ) {return i.hasNext( );}
public Object next( ) {return i.next( );}
public void remove( ) {
throw new UnsupportedOperationException( );
}
};
}
public boolean add(Object o){
throw new UnsupportedOperationException( );
}
public boolean remove(Object o) {
throw new UnsupportedOperationException( );
}
public boolean containsAll(Collection coll) {
return c.containsAll(coll);
}
public boolean addAll(Collection coll) {
throw new UnsupportedOperationException( );
}
public boolean removeAll(Collection coll) {
throw new UnsupportedOperationException( );
}
public boolean retainAll(Collection coll) {
throw new UnsupportedOperationException( );
}
public void clear( ) {
throw new UnsupportedOperationException( );
}
}
public static Set unmodifiableSet(Set s) {
return new UnmodifiableSet(s);
}