第一種是固定的一種泛型,第二種是隻要是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());
}
}