java泛型介紹

來源:互聯網
上載者:User

標籤:聲明   key   log   type   pre   integer   erb   rabl   ret   

泛型基礎   泛型類

  我們首先定義一個簡單的Box類:

public class Box {    private String object;    public void set(String object) { this.object = object; }    public String get() { return object; }}

  這是最常見的做法,這樣做的一個壞處是Box裡面現在只能裝入String類型的元素,今後如果我們需要裝入Integer等其他類型的元素,還必須要另外重寫一個Box,代碼得不到複用,使用泛型可以很好的解決這個問題。

public class Box<T> {    // T stands for "Type"    private T t;    public void set(T t) { this.t = t; }    public T get() { return t; }}

  

這樣我們的Box類便可以得到複用,我們可以將T替換成任何我們想要的類型:Box<Integer> integerBox = new Box<Integer>();Box<Double> doubleBox = new Box<Double>();Box<String> stringBox = new Box<String>();

  

泛型方法  看完了泛型類,接下來我們來瞭解一下泛型方法。聲明一個泛型方法很簡單,只要在傳回型別前面加上一個類似<K, V>的形式就行了:public class Util {    public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {        return p1.getKey().equals(p2.getKey()) &&               p1.getValue().equals(p2.getValue());    }}public class Pair<K, V> {    private K key;    private V value;    public Pair(K key, V value) {        this.key = key;        this.value = value;    }    public void setKey(K key) { this.key = key; }    public void setValue(V value) { this.value = value; }    public K getKey()   { return key; }    public V getValue() { return value; }}

  

我們可以像下面這樣去調用泛型方法:Pair<Integer, String> p1 = new Pair<>(1, "apple");Pair<Integer, String> p2 = new Pair<>(2, "pear");boolean same = Util.<Integer, String>compare(p1, p2);

  

邊界符

現在我們要實現這樣一個功能,尋找一個泛型數組中大於某個特定元素的個數,我們可以這樣實現:

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;}

  

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.