1. 程式人生 > >Class T泛型和萬用字元泛型的區別

Class T泛型和萬用字元泛型的區別

第一種是固定的一種泛型,第二種是隻要是Object類的子類都可以,換言之,任何類都可以,因為Object是所有類的根基類
固定的泛型指型別是固定的,比如:Interge,String. 就是<T extends Collection>

<? extends Collection> 這裡?代表一個未知的型別,
但是,這個未知的型別實際上是Collection的一個子類,Collection是這個萬用字元的上限.
舉個例子
class Test <T extends Collection> { }

<T extends Collection>其中,限定了構造此類例項的時候T是一個確定型別(具體型別),這個型別實現了Collection介面,
但是實現 Collection介面的類很多很多,如果針對每一種都要寫出具體的子類型別,那也太麻煩了,乾脆還不如用
Object通用一下。
<? extends Collection>其中,?是一個未知型別,是一個萬用字元泛型,這個型別是實現Collection介面即可。

_________________________上面講的是什麼鬼,當你知道引入萬用字元泛型的由來之後(下面程式碼由java1234.com提供)

The method take(Animal) in the type Test is not applicable for the arguments (Demo<Dog>)
The method take(Animal) in the type Test is not applicable for the arguments (Demo<Cat>)
The method take(Animal) in the type Test is not applicable for the arguments (Demo<Animal>)
當引入泛型之後,遇到這種情況,引數怎麼寫都不適合,總有2個方法不適用,為了給泛型類寫一個通用的方法,這時候就需要引入了 ?萬用字元的概念。

public class Demo <T extends Animal>{

    private T ob;

    public T getOb() {
        return ob;
    }

    public void setOb(T ob) {
        this.ob = ob;
    }

    public Demo(T ob) {
        super();
        this.ob = ob;
    }
    
    
public void print(){ System.out.println("T的型別是:"+ob.getClass().getName()); } }

public class Demo <T extends Animal>{

    private T ob;

    public T getOb() {
        return ob;
    }

    public void setOb(T ob) {
        this.ob = ob;
    }

    public Demo(T ob) {
        super();
        this.ob = ob;
    }
    
    public void print(){
        System.out.println("T的型別是:"+ob.getClass().getName());
    }
}