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)
你遍历的集合是,courses,而courses是Course对象的集合,it.next()返回的是Course对象并不是List<Course>集合
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);
}