該知識點是自己從書籍中學習的筆記。
從jdk1.5版本開始,java就引入了泛型。在沒有泛型之前,從集合中取出的對象都必須經過轉型,才能夠達到使用。在jdk1.5之前,如果往集合中插入了不同類型的對象的話,那麼在遍歷的時候就可能引起運行時轉型失敗。
泛型定義:A class or interface whose declaration has one or more type parameters is a generic class or interface [JLS, 8.1.2, 9.1.2].就是說一個類或者接口擁有一或者多種類型參數的聲明就是泛型類或者接口。
以下代碼會編譯出錯:
public class Test1 {
public static void main(String[] args) {
List<String> strings = new ArrayList<String>();
unsafeAdd(strings, new String("42"));
String s = strings.get(0); // Compiler
}
static void unsafeAdd(List<String> list, Object o) {
list.add(o);
}
}//The method add(String) in the type List<String> is not applicable for the arguments (Object)
當不知道具體類型的時候,可以使用“?”號來表示通用的參數類型,如:
static int numElementsInCommon(Set<?> s1, Set<?> s2){
。。。}
總之,如果使用jdk1.5版本的話,那麼就使用泛型。Set<Object>表示一個參數化類型,並且該Set裏面只能夠放Object類型的元素;Set<?>是一個通配符,表示Set中僅僅包含了一些未知類型的對象;Set是一個原生類型,沒有指定泛型。前兩者都是安全的,但是後者不是安全的。