0
点赞
收藏
分享

微信扫一扫

Java 中迭代器的注意事项

栖桐 2022-04-15 阅读 100
java

*迭代器的使用:
 *        1)集合获取迭代器的时候,
 *            集合里面存储的类型是什么类型,心里要清楚,转换会出现类转换异常(没有使用泛型!)
 *        2)next()不能使用多次  ,结果不匹配(next()使用拿到了迭代器中所有的对象)
 *            Object obj = 迭代器对象.next();
 * 求:使用Collection集合存储自定义对象:学生对象(4个),有姓名和年龄,使用迭代器遍历集合!

public class InteratorDemo2 {
	public static void main(String[] args) {
//		创建集合对象
		Collection c=new ArrayList();
		//创建学生
		Student s1=new Student("张三",20);
		Student s2=new Student("李四",20);
		Student s3=new Student("王五",20);
		Student s4=new Student("王二",20);
		//添加元素
		c.add(s1);
		c.add(s2);
		c.add(s3);
		c.add(s4);
		//获取迭代器对象
		Iterator iterator=c.iterator();
		while(iterator.hasNext()) {
			Student s=(Student)(iterator.next());
			System.out.println(s.getName()+" "+s.getAge());
		}
	}
}

 

举报

相关推荐

0 条评论