Java泛型代碼例子

來源:互聯網
上載者:User

標籤:泛型   代碼   java   

Java泛型代碼例子

一篇代碼勝過千言萬語

package com.apkkids.javalanguage;import java.util.ArrayList;import java.util.List;/** * @author wxb * Java泛型例子 */public class GenericTest {    //泛型介面    public interface MyCollection<T>{        public T get(int position );        public T add(T t);    }    //泛型介面繼承    public interface MyList<T> extends MyCollection<T>{}    //泛型類    public static class MyListImpl<T> implements MyList<T>{        public T get(int position) {            System.out.println("get value at position "+ position);            return null;        }        public T add(T t) {            System.out.println("add "+t.toString());            return null;        }    }    //要用到的一組類    public static class Fruit{}    public static class Apple extends Fruit{}    public static class Strawberry extends Fruit{}    public static class FujiApple extends Apple{}    /**     * @param args     */    public static void main(String[] args) {        //執行個體化泛型類        MyList<String> strlist = new MyListImpl<String>();        strlist.add("test");        strlist.get(0);        //下面的代碼說明:List<Apple>不是List<Fruit>的子類,用更通俗的話,泛型型別跟其是否子類型沒有任何關係。//      List<Apple> apples = new ArrayList<Apple>();//      List<Fruit> fruits = apples;        // 使用 ? extends 萬用字元,List<Apple>和List<Strawberry>的對象都可以賦值給List<? extends Fruit>        List<Apple> apples = new ArrayList<Apple>();        List<Strawberry> strawberrys = new ArrayList<Strawberry>();        List<? extends Fruit> fruits = apples;        fruits = strawberrys;        //使用 ? super 萬用字元,List<Fruit>的對象可以賦值給List<? super Apple>        List<Fruit> fruits2 = new ArrayList<Fruit>();        List<? super Apple> apples2 = fruits2;//      總結 ? extends 和 the ? super 萬用字元的特徵,我們可以得出以下結論://      1.如果你想從一個資料類型裡擷取資料,使用 ? extends 萬用字元        fruits.get(0);        //下面三行都會編譯報錯//      fruits.add(new Apple());//      fruits.add(new Strawberry());//      fruits.add(new Fruit());        //      2.如果你想把對象寫入一個資料結構裡,使用 ? super 萬用字元        apples2.add(new Apple());        apples2.add(new FujiApple());        Object o = apples2.get(0);  //取出時只能得到Obejct對象//      3.如果你既想存,又想取,那就別用萬用字元。    }}

Java泛型代碼例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.