隨筆-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 閱讀(1136) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 华阴市| 琼结县| 屏山县| 嘉荫县| 伊春市| 平度市| 巴塘县| 宁津县| 庐江县| 清水县| 肃南| 阿克陶县| 彰武县| 赤壁市| 克拉玛依市| 温泉县| 淅川县| 深水埗区| 湖州市| 当涂县| 佳木斯市| 上杭县| 慈溪市| 新巴尔虎右旗| 郸城县| 丰顺县| 仙游县| 左云县| 贡嘎县| 胶南市| 定西市| 吴川市| 隆尧县| 威远县| 深州市| 永康市| 宁南县| 若羌县| 绥芬河市| 荣成市| 凤庆县|