【The Java? Tutorials】【Generics】4. Bounded Type Parameters

What and Why

There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.

How

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound.
注意: In this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces)

public class Box<T> {

    private T t;          

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }

    public <U extends Number> void inspect(U u){
        System.out.println("T: " + t.getClass().getName());
        System.out.println("U: " + u.getClass().getName());
    }

    public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.set(new Integer(10));
        integerBox.inspect("some text"); // error: this is still String!
    }
}

In addition to limiting the types you can use to instantiate a generic type, bounded type parameters allow you to invoke methods defined in the bounds:

public class NaturalNumber<T extends Integer> {

    private T n;

    public NaturalNumber(T n)  { this.n = n; }

    public boolean isEven() {
        return n.intValue() % 2 == 0;
    }

    // ...
}

上面的例子中,由于限定了T是Integer的子類,所以n可以直接調(diào)用Integer中的方法intValue。

Multiple Bounds

如果有多個限定,寫法如下:

<T extends B1 & B2 & B3>

假設有3個限定A, B, C,其中A是一個類,B和C都是接口:

Class A { /* ... */ }
interface B { /* ... */ }
interface C { /* ... */ }

那么應該把A放在最前面,否則會報錯:

class D <T extends A & B & C> { /* ... */ }
class D <T extends B & A & C> { /* ... */ }  // compile-time error

Generic Methods and Bounded Type Parameters

假設我們要實現(xiàn)以下代碼的功能:

public static <T> int countGreaterThan(T[] anArray, T elem) {
    int count = 0;
    for (T e : anArray)
        if (e > elem)  // compiler error
            ++count;
    return count;
}

但是這段代碼會出現(xiàn)編譯錯誤,因為T的具體類型是未知的,不能直接通過e > elem判斷大?。ㄖ挥袛?shù)值類型才能直接這樣判斷)。這個時候我們可以使用Bounded Type Parameters來很好的解決這個問題:

public interface Comparable<T> {
    public int compareTo(T o);
}
public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
    int count = 0;
    for (T e : anArray)
        if (e.compareTo(elem) > 0)
            ++count;
    return count;
}

我們限定T必須實現(xiàn)Comparable<T>接口,而Comparable<T>接口中定義了比較兩個T的大小的方法。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,817評論 0 10
  • 周毅 平地無聲東山靜, 寂寞玉蘭聽雨聲。 古柳聳立須眉綠, 空院不聞童子語。 早...
    行走的水云劍閱讀 495評論 1 1
  • 看著看著就哭笑不得了,怎么辦?實話不好說,違心的話也不好說,糾結(jié)ing
    七月紫蘇閱讀 346評論 0 0
  • 這個題目呢,很早之前就想寫了,不是針對某個人,也不是因為我們一起寫作的小伙伴,而是今年發(fā)現(xiàn)不管是微課還是一些付費課...
    豆豆在成長閱讀 318評論 0 0
  • 昨天打電話過來溝通,不知道什么時候可以開始調(diào)解,希望可以早點解決掉。我是一個比較急的個性,有個事情在心里很難過,...
    努力活成個笑話閱讀 287評論 0 0

友情鏈接更多精彩內(nèi)容