泛型
public class Box<T>
{
private T t;
public void set(T t){ this.t = t;}
public T get(){ return t;}
public static void main(String[] args)
{
Box<Integer> integerBox = new Box<>();
Box<String> StringBox = new Box<>();
integerBox.set(3);
StringBox.set("你好,世界!");
System.out.println(integerBox.get());
System.out.println(StringBox.get());
}
}
使用泛型的好處:
- 讓一些類型錯誤在編譯時就被發(fā)現(xiàn)帽氓,不必等到運(yùn)行時。
- 使用類型參數(shù),可以實(shí)現(xiàn)代碼復(fù)用的功能岁钓。上面的代碼的T就是類型參數(shù)翰撑。
詳細(xì)內(nèi)容見下面兩個鏈接的內(nèi)容
Java泛型詳解
十道Java泛型面試題