posts - 1, comments - 0, trackbacks - 0, articles - 1
            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          Jdk1.5中支持了泛型,在泛型的使用過程中經(jīng)常會遇到這樣一類問題

          類Parent
          public ? class ?Parent? {
          ?
          // your?code
          }


          類Child
          public ? class ?Child? extends ?Parent {
          // ?your?code
          }


          調(diào)用的地方

          import ?java.util.ArrayList;
          import ?java.util.List;

          import ?com.test.Child;


          public ? class ?Test? {
          ????
          public ? static ? void ?doTest(List < Parent > ?list) {
          ????????
          ????}

          ????
          public ? static ? void ?main(String[]?args) {
          ????????List
          < Parent > ?parentList? = ? new ?ArrayList < Parent > ();
          ????????List
          < Child > ?childList? = ? new ?ArrayList < Child > ();
          ????????doTest(parentList);
          ????????
          // 注意這里編譯錯誤
          ????????doTest(childList);
          ????????
          ????}

          }


          你會發(fā)現(xiàn)編譯錯誤,但是在我們的需求中Child的集合類是可以代替Parent的集合類來使用的,但是因為編譯器不認同,因為兩個集合類之間沒有直接的繼承關(guān)系。如果實現(xiàn)呢?在Jdk1.5的Source中我們找到了答案,隨便找一個帶有泛型的類,點進去可以看到泛型的定義,例如ArrayList<E>? HashMap<K,V>? 等等
          這里以ArrayList為例:注意addAll這個函數(shù)

          public ? boolean ?addAll(Collection <? ? extends ?E > ?c)? {
          ????Object[]?a?
          = ?c.toArray();
          ????????
          int ?numNew? = ?a.length;
          ????ensureCapacity(size?
          + ?numNew);?? // ?Increments?modCount
          ????????System.arraycopy(a,? 0 ,?elementData,?size,?numNew);
          ????????size?
          += ?numNew;
          ????
          return ?numNew? != ? 0 ;
          ????}

          ok,明白了,這個就是問號的作用.更改我們的函數(shù)

          import ?java.util.ArrayList;
          import ?java.util.List;

          public ? class ?Test? {
          ????????
          // 這里更改一下,利用問號解決問題?
          ???? public ? static ? void ?doTest(List <? ? extends ?Parent > ?list) {
          ????????
          ????}

          ????
          public ? static ? void ?main(String[]?args) {
          ????????List
          < Parent > ?parentList? = ? new ?ArrayList < Parent > ();
          ????????List
          < Child > ?childList? = ? new ?ArrayList < Child > ();
          ????????doTest(parentList);
          ????????
          // 注意這里編譯正確????????
          ????????doTest(childList)????}

          }



          ?



          dreamstone 2007-02-10 23:46 發(fā)表評論

          文章來源:http://www.aygfsteel.com/dreamstone/archive/2007/02/10/99195.html

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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 从江县| 大冶市| 三都| 民乐县| 濉溪县| 固安县| 怀仁县| 黑水县| 会东县| 喀喇| 兰溪市| 剑阁县| 金阳县| 巩义市| 讷河市| 木兰县| 高雄县| 扶绥县| 蕉岭县| 厦门市| 南投县| 阿尔山市| 康乐县| 芦山县| 宁德市| 玉田县| 万山特区| 绥化市| 华宁县| 石景山区| 剑阁县| 巴马| 灵璧县| 博爱县| 津南区| 武邑县| 宁安市| 临汾市| 泰州市| 资中县| 卫辉市|