爲什麼要引入泛型--->定義輸入對象類型,方便使用、安全
1)對於一個Student類,存放一個Object對象,向內部存儲數據,使用以下方法:
沒有泛型的數據存儲與讀取
創建一個PO類(JavaBean),實體化對象,存儲數據的類
/**
* PO類(實體化對象,用於存儲數據的類),JavaBean
* @author Administrator
*
*/
public class Student {
private Object obj;
public Student(Object obj) {
super();
this.obj = obj;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
}
在不引入泛型的情況下進行數據存儲與提取
/**
* 沒有泛型的類存儲數據
* 存放不同類型數據時需要進行多次類型檢查和轉換
* @author Administrator
*
*/
public class StuApp {
public static void main(String[] args) {
Student stu = new Student(80);
Object obj = stu.getObj();
//類型檢查
if (obj instanceof Integer) {
//強制類型轉換
Integer score = (Integer) obj;
}
Student stu1 = new Student("優秀");
Object obj1 = stu.getObj();
//類型檢查
if (obj1 instanceof String) {
//強制類型轉換
String score = (String) obj1;
}
}
}