java泛型中 和的區別---轉寄

來源:互聯網
上載者:User
java泛型中<? super T> 和<? extends T>的區別

經常發現有List<? super T>、Set<? extends T>的聲明,是什麼意思呢。
<? super T>表示包括T在內的任何T的父類,<? extends T>表示包括T在內的任何T的子類,下面我們詳細分析一下兩種萬用字元具體的區別。 extends

List<? extends Number> foo3的萬用字元聲明,意味著以下的賦值是合法的:

// Number "extends" Number (in this context)List<? extends Number> foo3 = new ArrayList<? extends Number>();// Integer extends NumberList<? extends Number> foo3 = new ArrayList<? extends Integer>();// Double extends NumberList<? extends Number> foo3 = new ArrayList<? extends Double>();

讀取操作通過以上給定的指派陳述式,你一定能從foo3列表中讀取到的元素的類型是什麼呢。你可以讀取到Number,因為以上的列表要麼包含Number元素,要麼包含Number的類元素。
你不能保證讀取到Integer,因為foo3可能指向的是List<Double>。
你不能保證讀取到Double,因為foo3可能指向的是List<Integer>。
寫入操作過以上給定的指派陳述式,你能把一個什麼類型的元素合法地插入到foo3中呢。
你不能插入一個Integer元素,因為foo3可能指向List<Double>。
你不能插入一個Double元素,因為foo3可能指向List<Integer>。
你不能插入一個Number元素,因為foo3可能指向List<Integer>。
你不能往List<? extends T>中插入任何類型的對象,因為你不能保證列表實際指向的類型是什麼,你並不能保證列表中實際儲存什麼類型的對象。唯一可以保證的是,你可以從中讀取到T或者T的子類。 super

現在考慮一下List<? super T>。
List<? super Integer> foo3的萬用字元聲明,意味著以下賦值是合法的:

// Integer is a "superclass" of Integer (in this context)List<? super Integer> foo3 = new ArrayList<Integer>();// Number is a superclass of IntegerList<? super Integer> foo3 = new ArrayList<Number>();// Object is a superclass of IntegerList<? super Integer> foo3 = new ArrayList<Object>();
讀取操作通過以上給定的指派陳述式,你一定能從foo3列表中讀取到的元素的類型是什麼呢。你不能保證讀取到Integer,因為foo3可能指向List<Number>或者List<Object>。
你不能保證讀取到Number,因為foo3可能指向List<Object>。
唯一可以保證的是,你可以讀取到Object或者Object子類的對象(你並不知道具體的子類是什麼)。 寫入操作通過以上給定的指派陳述式,你能把一個什麼類型的元素合法地插入到foo3中呢。你可以插入Integer對象,因為上述聲明的列表都支援Integer。
你可以插入Integer的子類的對象,因為Integer的子類同時也是Integer,原因同上。
你不能插入Double對象,因為foo3可能指向ArrayList<Integer>。
你不能插入Number對象,因為foo3可能指向ArrayList<Integer>。
你不能插入Object對象,因為foo3可能指向ArrayList<Integer>。 PECS

請記住PECS原則:生產者(Producer)使用extends,消費者(Consumer)使用super。

生產者使用extends
如果你需要一個列表提供T類型的元素(即你想從列表中讀取T類型的元素),你需要把這個列表聲明成<? extends T>,比如List<? extends Integer>,因此你不能往該列表中添加任何元素。

消費者使用super
如果需要一個列表使用T類型的元素(即你想把T類型的元素加入到列表中),你需要把這個列表聲明成<? super T>,比如List<? super Integer>,因此你不能保證從中讀取到的元素的類型。

即是生產者,也是消費者
如果一個列表即要生產,又要消費,你不能使用泛型萬用字元聲明列表,比如List<Integer>。

例子
請參考java.util.Collections裡的copy方法(JDK1.7):

 /**     * Copies all of the elements from one list into another.  After the     * operation, the index of each copied element in the destination list     * will be identical to its index in the source list.  The destination     * list must be at least as long as the source list.  If it is longer, the     * remaining elements in the destination list are unaffected. <p>     *     * This method runs in linear time.     *     * @param  dest The destination list.     * @param  src The source list.     * @throws IndexOutOfBoundsException if the destination list is too small     *         to contain the entire source List.     * @throws UnsupportedOperationException if the destination list's     *         list-iterator does not support the <tt>set</tt> operation.     */    public static <T> void copy(List<? super T> dest, List<? extends T> src)     {        int srcSize = src.size();        if (srcSize > dest.size())            throw new IndexOutOfBoundsException("Source does not fit in dest");        if (srcSize < COPY_THRESHOLD ||(src instanceof RandomAccess && dest instanceof RandomAccess))         {            for (int i=0; i<srcSize; i++)                dest.set(i, src.get(i));        }         else         {            ListIterator<? super T> di=dest.listIterator();            ListIterator<? extends T> si=src.listIterator();            for (int i=0; i<srcSize; i++)             {                di.next();                di.set(si.next());            }        }    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.