在Java中,有時候會遇到邏輯相似但型態可能不同的類別
例如:
test1.java
package mypackage; public class test1 { private int num; public void setVal(int num) { this.num = num; } public int getVal() { return this.num; } }
test2.java
package mypackage; public class test2 { private String str; public void setVal(String str) { this.str = str; } public String getVal() { return this.str; } }
index.java
import mypackage.test1; import mypackage.test2; public class index { public static void main(String[] argv) { test1 t1 = new test1(); test2 t2 = new test2(); t1.setVal(123); System.out.println(t1.getVal()); t2.setVal("This is test"); System.out.println(t2.getVal()); } }
上面範例除了還要再新增一個class之外,如果遇到後續邏輯修改,也要重複將類似邏輯的class修完,非常的浪費時間
這時候使用泛型就可以解決上述的問題
generics.java
package mypackage; public class generics<T> { private T val; public void setVal(T val) { this.val = val; } public T getVal() { return this.val; } }
index.java
import mypackage.generics; public class index { public static void main(String[] argv) { generics<Integer> t1 = new generics<Integer>(); generics<String> t2 = new generics<String>(); t1.setVal(123); System.out.println(t1.getVal()); t2.setVal("This is test"); System.out.println(t2.getVal()); } }
另外也可以限制泛型的類別,限制可以使用的類別()
package mypackage; public class generics<T extends List> { //d這樣只能使用像ArrayList、LinkedList等型別 }