Java编程中注意的问题

让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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值