泛型集合怎么用迭代器遍歷元素?
public?class?TestGeneric?{
public?List<Course>?courses;
public?TestGeneric(){
this.courses?=?new?ArrayList<Course>();?
}
//測(cè)試添加元素
public?void?TestAdd(){
System.out.println("添加課程:");
Course?cr1?=?new?Course("1","習(xí)近平會(huì)議講話精神");
courses.add(cr1);
System.out.println(cr1.id+":"+cr1.name);
Course?cr2?=?new?Course("2","Java基礎(chǔ)");
courses.add(cr2);
System.out.println(cr2.id+":"+cr2.name);
}
public?void?TestIterator(){
System.out.println("有如下課程待選:(使用Iterator迭代器循環(huán)遍歷集合中的元素)");
Iterator?it?=?courses.iterator();
while(it.hasNext()){
List<Course>?cr4?=?(List<Course>)?it.next();
????System.out.println(cr4);
}
}
這樣為什么不可以呢?錯(cuò)哪兒了?
有如下課程待選:(使用Iterator迭代器循環(huán)遍歷集合中的元素)
java.lang.ClassCastException: com.imooc.collection.Course cannot be cast to java.util.List
at com.imooc.collection.TestGeneric.TestIterator(TestGeneric.java:41)
at com.imooc.collection.TestGeneric.main(TestGeneric.java:51)
有如下課程待選:(使用Iterator迭代器循環(huán)遍歷集合中的元素)
java.lang.ClassCastException: com.imooc.collection.Course cannot be cast to java.util.List
at com.imooc.collection.TestGeneric.TestIterator(TestGeneric.java:41)
at com.imooc.collection.TestGeneric.main(TestGeneric.java:51)
2016-12-09
你遍歷的集合是,courses,而courses是Course對(duì)象的集合,it.next()返回的是Course對(duì)象并不是List<Course>集合
2016-12-09
?while(it.hasNext()){
????????????List<Course>?cr4?=?(List<Course>)?it.next();
????????????System.out.println(cr4);
????????}
改為
?while(it.hasNext()){
??????????? Course cr4?= (Course)?it.next();
????????????System.out.println(cr4);
????????}