泛型集合怎么用迭代器遍历元素?
public class TestGeneric {
public List<Course> courses;
public TestGeneric(){
this.courses = new ArrayList<Course>();
}
//测试添加元素
public void TestAdd(){
System.out.println("添加课程:");
Course cr1 = new Course("1","习近平会议讲话精神");
courses.add(cr1);
System.out.println(cr1.id+":"+cr1.name);
Course cr2 = new Course("2","Java基础");
courses.add(cr2);
System.out.println(cr2.id+":"+cr2.name);
}
public void TestIterator(){
System.out.println("有如下课程待选:(使用Iterator迭代器循环遍历集合中的元素)");
Iterator it = courses.iterator();
while(it.hasNext()){
List<Course> cr4 = (List<Course>) it.next();
System.out.println(cr4);
}
}
这样为什么不可以呢?错哪儿了?
有如下课程待选:(使用Iterator迭代器循环遍历集合中的元素)
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迭代器循环遍历集合中的元素)
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)