一、使用泛型的優點
1、編譯時可以檢查可能的錯誤,使程序更加可靠;
Comparable c = new Date();
System.out.println(c.compareTo("red"));//能夠正常編譯,在運行時才報錯
Comparable<Date> c = new Date();
System.out.println(c.compareTo("red"));//在編譯時就報錯,無法通過編譯
2、無需類型轉換
ArrayList<String> list = new ArrayList<String>();
list.add("Red");
String s = list.get(0);
//在JDK1.5之前需要轉換成String類型
String s = (String)(list.get(0));
二、T,E,K,V區別
- ? 表示不確定的java類型
- T (type) 表示具體的一個java類型
- K V (key value) 分別代表java鍵值中的Key Value
- E (element) 代表Element
//T和E的作用和效果是一樣的
public void test<T>()
public void test<E>()
三、泛型類和接口的定義
//泛型類
public class GenericStack<E> {
private ArrayLIst<E> list = new ArrayList<E>();
public GenericStack() {}
public E peek() {
return list.get(list.size() - 1);
}
public void push(E 0) {
list.add(o);
}
}
//使用
GenericStack<String> stack = new GenericStack<String>();
stack.push("Red");
//泛型接口
public interface Comparable<T> {
public int compareTo(T o);
}
四、泛型方法
public class GenericMethodDemo {
public static <E> void print(E[] list) {}
//調用
String[] strings = {"red","green","blue"}
GenericMethodDemo.<String>print(strings);
}
public class Max {
public static Comparable max(Comparable o1, Comparable o2) {
if(o1.comparTo(o2) > 0) {
return o1;
} else {
return o2;
}
}
}
//將會在運行時報錯,因爲不能將字符串與整數進行比較
Max1.max("Welcom", 23);
public class Max1 {
public static <E extends Comparable<E>> E max(E o1, E o2) {
if(o1.comparTo(o2) > 0) {
return o1;
} else {
return o2;
}
}
}
//將會編譯不過,要求兩個參數必須是相同的類型
Max1.max("Welcom", 23);
五、通配泛型
有三種類型
?非受限通配,和? extends Object是一樣的
? extends T 受限通配,表示T和T的子類
? super T 下限通配,表示T和T的父類