泛型其实就是在集合创建是就设定集合中放置何种类型的对象。这样以后读出的元素时就不需要强制转换了。如果不是泛型,则无论向集合中添加何种对象都是当做对象Object,所以取出来也是Object,因此需要强制转换。
public class Student{
private String sname,sno;
private int score;
public Student(String sname,String sno,int score){
this.sname=sname;
this.sno=sno;
this.score=score;
}
public void setSname(String sname){
this.sname=sname;
}
public void setSno(String sno){
this.sno=sno;
}
public void setScore(int score){
this.score=score;
}
public String getSname(){
return sname;
}
pubilc String getSno(){
return sno;
}
public int getScore(){
return score;
}
}
例子1:没有使用泛型的集合示例
public static void main(String args){
List list=new ArrayList();
Student s1=new Student("1001","黄一",67);
Student s2=new Student("1002","黄二",87);
Student s3=new Student("1003","黄三",97);
list.add(s1);
list.add(s2);
list.add(s3);
Iterator it=list.itrator();//迭代器搜索,类似把散落的hashmap连成一条线进行搜索
while(it.hasNext()){
Student s=(Student)it.next();//①
System.out.println(s.getSname()+","+s.getSno()+","+s.getScore());
}
}
在①行中,由于每次取出来的对象都进行了强制转换,至于转换是否错误,编译时无法检查。如果错误,运行时会产生异常,显然类型是不安全的。因此,我们采用使用泛型的方法。
例子2:使用泛型实例
List<Student> list=new ArrayList<Student>();//②
Student s1=new Student("1001","黄一",67);
Student s2=new Student("1002","黄二",87);
Student s3=new Student("1003","黄三",97);
list.add(s1);
list.add(s2);
list.add(s3);
for(int i=0;i<list.size();i++){
Student s=list.get(i);//③
System.out.println(s.getSname()+","+s.getSno()+","+s.getScore());
}
其中,第②行部分在定义了泛型,保证List中的元素都是Student类型。因此③行取出的List中的元素时,不必进行强制转换。