【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>

假設(shè)有3個限定A, B摩瞎, C旗们,其中A是一個類构灸,B和C都是接口:

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

那么應(yīng)該把A放在最前面喜颁,否則會報錯:

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

Generic Methods and Bounded Type Parameters

假設(shè)我們要實現(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)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市城侧,隨后出現(xiàn)的幾起案子嫌佑,更是在濱河造成了極大的恐慌,老刑警劉巖揩魂,帶你破解...
    沈念sama閱讀 219,539評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件火脉,死亡現(xiàn)場離奇詭異倦挂,居然都是意外死亡担巩,警方通過查閱死者的電腦和手機涛癌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評論 3 396
  • 文/潘曉璐 我一進店門拳话,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事笨鸡⌒魏模” “怎么了辙浑?”我有些...
    開封第一講書人閱讀 165,871評論 0 356
  • 文/不壞的土叔 我叫張陵判呕,是天一觀的道長送滞。 經(jīng)常有香客問我,道長但金,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,963評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮求厕,結(jié)果婚禮上叠洗,老公的妹妹穿的比我還像新娘灭抑。我一直安慰自己,他們只是感情好忘嫉,可當我...
    茶點故事閱讀 67,984評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著访递,像睡著了一般同辣。 火紅的嫁衣襯著肌膚如雪旱函。 梳的紋絲不亂的頭發(fā)上棒妨,一...
    開封第一講書人閱讀 51,763評論 1 307
  • 那天,我揣著相機與錄音拘泞,去河邊找鬼蜈出。 笑死铡原,一個胖子當著我的面吹牛燕刻,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播请唱,決...
    沈念sama閱讀 40,468評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼本橙!你這毒婦竟也來了甚亭?” 一聲冷哼從身側(cè)響起击胜,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤暇唾,失蹤者是張志新(化名)和其女友劉穎信不,沒想到半個月后亡呵,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體锰什,經(jīng)...
    沈念sama閱讀 45,850評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡梭姓,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,002評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了铸题。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片丢间。...
    茶點故事閱讀 40,144評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡诀艰,死狀恐怖其垄,靈堂內(nèi)的尸體忽然破棺而出绿满,到底是詐尸還是另有隱情虽风,我是刑警寧澤辜膝,帶...
    沈念sama閱讀 35,823評論 5 346
  • 正文 年R本政府宣布茎毁,位于F島的核電站七蜘,受9級特大地震影響橡卤,放射性物質(zhì)發(fā)生泄漏碧库。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,483評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望迁匠。 院中可真熱鬧城丧,春花似錦芙贫、人聲如沸磺平。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至舔痪,卻和暖如春锄码,著一層夾襖步出監(jiān)牢的瞬間滋捶,已是汗流浹背重窟。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評論 1 272
  • 我被黑心中介騙來泰國打工炒考, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人知给。 一個月前我還...
    沈念sama閱讀 48,415評論 3 373
  • 正文 我出身青樓轩勘,卻偏偏與公主長得像绊寻,于是被迫代替她去往敵國和親澄步。 傳聞我的和親對象是個殘疾皇子祠肥,可洞房花燭夜當晚...
    茶點故事閱讀 45,092評論 2 355

推薦閱讀更多精彩內(nèi)容

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