1. 程式人生 > >泛型知識

泛型知識

1.泛型的提出

:是一種把型別明確的工作推遲到建立對或者呼叫方法的時候才去明確的特殊的型別。引數化型別,把型別當作引數一樣的傳遞。

2.泛型的優點

(1): 把執行時期的問題提前到了編譯期間
(2): 避免了強制型別轉換
(3):優化了程式設計,解決了黃色警告線

 注意:泛型只在編譯期有效  但在執行期就擦除了

3.泛型引用時的常見錯誤:

class Animal {}
class Dog extends Animal{}
class Cat extends Animal{}
class GenericDemo {
public static void main(String[] args) {
Collection<Animal> c2 = new ArrayList<Dog>();
Collection<Animal> c3 = new ArrayList<Cat>();
Collection<? extends Animal> c4 = new ArrayList<Object>();
Collection<? super Animal> c10 = new ArrayList<Dog>();
Collection<? super Animal> c11 = new ArrayList<Cat>();
}
}

(1)泛型時若等號左邊給定了格式,等號右邊必須保持一致或不寫

(2)若等號左邊為<? extends X>時,等號右邊必須是X的子類或其本身

(3)若等號左邊為<? extends X>時,等號右邊必須是X的父類或其本身

(4)只有當等號左邊為<?>時,格式才能變化,但當呼叫的時候只能返回Object型別的資料,也就是必須向下轉型才能使用