java为什么采用泛型

泛型其实就是在集合创建是就设定集合中放置何种类型的对象。这样以后读出的元素时就不需要强制转换了。如果不是泛型,则无论向集合中添加何种对象都是当做对象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中的元素时,不必进行强制转换。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值