随笔-159  评论-114  文章-7  trackbacks-0

 传统我们都是定一个类型,带T的

public class RandomSelection<T> {

  
private java.util.Random random = new Random();

  
private ArrayList<T> list;

  
public RandomSelection() {

     list 
= new ArrayList<T>();

  }


  
public void add(T element) {

     list.add(element);

  }


  
public T getRandomElement() {

     
int index = random.nextInt(list.size());

     
return list.get(index);

  }



}


直接来使用。当我们new RandomSelection<String>()  new RandomSelection<Integer>() 的时候,里面的方法的类型,也就确定了。

public interface ISomeReason<extends Enum<X>> {

   
public X getImplClassType();

}

实现一个子类。这里看到继承是传入了接口泛型中的X参数,参数就是实现类自己的类型。

public enum ATypeReason implements ISomeReason<ATypeReason> {

   ABC(
1),
   DEF(
2),

   ;
   
int index;

   
private ATypeReason(int param)
   
{
      
this.index = param;
   }


   
public int getIndex()
   
{
       
return this.index;
   }


   @Override
   
public ATypeReason getImplClassType() {
      
return this
   }


}

你也可以直接实现,不传入X,那么在使用这个类型的实例去传入某一个指定类型的方法参数时,会提示错误,不利于代码健壮性。

public class MainTest {

   
public static void useATypeReason(ISomeReason<ATypeReason> reason)
{
    sysout(reason.getImplClassType().getIndex());
}


   
//ATypeReason的类型没有指定泛型参数适用于掉这个接口
   public static void dontCareParamType(ISomeReason<?> reason)
   
{
      sysout(reason.getImplClassType());
      
//不能调用
       sysout(reason.getImplClassType().getIndex());
   }


}

你可以把ISomeReason接口定义如下,更严格。

public interface ISomeReason<extends Enum<E> & ISomeReason<E>> {

   
public E type();

}



posted on 2010-06-29 14:08 北国狼人的BloG 阅读(1117) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: