Java泛型中的? super T文法

來源:互聯網
上載者:User

? super T 文法將泛型類限制為所有T的超類(包括T自身),但只能用於參數中,不可以在傳回值用加以限定。
如果不加以限定,假設某個函數頭為
? super Manager get()
由於編譯器不知道該方法究竟會返回什麼類,這樣就只能用Object類來接收了。

該文法常用的一個情況是泛型類的比較
java.util.TreeSet<E> 代表一個有序的元素為E的樹,它其中的一個構造器需要一個Comparator類來比較兩個元素,以E為String類時為例,此時的Comparator可以是Comparator<String>,也可以是Comparator<Object>,但Comparator<Integer>就不行,如何表示這樣的限制呢?
jdk原始碼中是這樣的:
public TreeSet(Comparator<? super E> c)
這樣就保證了傳給構造器的Comparator是可以進行E元素的比較的。

另一個例子,java.util.Collections的max方法用於獲得一個容器中的最大值,這個函數頭可以這樣寫:
public static <T extends Comparable<T>>  T max(Collection<T> coll)

這樣就限定T為能和自己比較的類,過於嚴格,jdk源碼是這樣的:

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
    Iterator<? extends T> i = coll.iterator();
    T candidate = i.next();

    while(i.hasNext()) {
    T next = i.next();
    if (next.compareTo(candidate) > 0)
        candidate = next;
    }
    return candidate;
}

很嚴謹的函數頭,但是限定方面比較寬

聯繫我們

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