//没有泛型之前存在的问题
List list =newArrayList();//需求:存入学生成绩
list.add(34);
list.add(23);//问题一:类型不安全,可以存入其他类型的数据
list.add("Tom");for(Object score : list){
//问题二:类型转换异常int num =(int)score;}
Second, use generics in collections
The collection interface or collection class is modified to a generic structure after JDK5
When instantiating a collection class, you can specify a specific generic type
The generic type must be a class, not a basic data type
If the instantiation does not specify a specific generic type, the default is Object
public Person<T>{
T name;publicPerson(T name){
this.name = name;}publicvoidsetName(T name){
this.name = name;}public T getName(){
return name;}}//如果定义了泛型类,在实例化对象时没有使用,则默认是Object
Person p =newPerson();//建议在实例化对象时,指定泛型的类型
Person<String> p1 =newPerson<>();