1.泛型的基礎概念java
泛型實現了參數化類型的概念,使代碼能夠應用於多種類型。ide
+ 簡單泛型this
public class Hold<T> { private T a; public Hold(T a){ this.a = a; }
public T getA() { return a; }
public void setA(T a) { this.a = a; } }
+ 泛型接口spa
public interface Generator<T> { T test(); }
+ 泛型方法code
public class Hold{ public <T> void f(T a){ System.out.println(a.getClass().getName()); }}
# 2.泛型的擦除orm
考點:在泛型代碼內部,沒法得到任何有關泛型參數類型的信息。接口
+ 考題1get
class c1 = new ArrayList<String>().getClass(); class c2 = new ArrayList<Integer>().getClass(); System.out.println(c1 == c2); 答案:true
+ 考題2it
class Frob {}class Fnorkle {}class Quark<Q> {}class Particle<POSITION,MOMENTUM> {}
public class LostInformation { public static void main(String[] args) { List<Frob> list = new ArrayList<Frob>(); Map<Frob,Fnorkle> map = new HashMap<Frob,Fnorkle>(); Quark<Fnorkle> quark = new Quark<Fnorkle>(); Particle<Long,Double> p = new Particle<Long,Double>(); System.out.println(Arrays.toString( list.getClass().getTypeParameters())); System.out.println(Arrays.toString( map.getClass().getTypeParameters())); System.out.println(Arrays.toString( quark.getClass().getTypeParameters())); System.out.println(Arrays.toString( p.getClass().getTypeParameters())); }}
/* Output:[E][K, V][Q][POSITION, MOMENTUM]*///:~
# 3.泛型的邊界io
將某個參數限制爲某個類型的子集。爲了執行這種限制,Java 泛型重用了extends 關鍵字。
interface HasColor { java.awt.Color getColor(); }
class Colored<T extends HasColor> { T item; Colored(T item) { this.item = item; } T getItem() { return item; } // The bound allows you to call a method: java.awt.Color color() { return item.getColor(); }}