为了账号安全,请及时绑定邮箱和手机立即绑定

泛型集合怎么用迭代器遍历元素?

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)


正在回答

2 回答

你遍历的集合是,courses,而courses是Course对象的集合,it.next()返回的是Course对象并不是List<Course>集合

0 回复 有任何疑惑可以回复我~
#1

shaoxiao64017599 提问者

非常感谢!
2016-12-09 回复 有任何疑惑可以回复我~
#2

shaoxiao64017599 提问者

泛型的好处不是可以按指定的类型获取集合元素?这里不是已经规定其为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);

        }


0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

泛型集合怎么用迭代器遍历元素?

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号