package demo01;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo01Iterator {
public static void main(String[] args) {
//创建一个集合对象
Collection<String> coll=new ArrayList<>();
//往集合中添加元素
coll.add("易晨");
coll.add("易轩");
coll.add("易墨");
coll.add("易凡");
coll.add("易一");
/*
1.使用集合中的方法iteator()获取迭代器的实现类对象,使用Iterator接口接收(多态)
注意:
Iterator<E>接口也是有泛型的,迭代器的泛型跟着集合走,集合是什么泛型,迭代器就是什么泛型
*/
Iterator<String> it=coll.iterator();
/*
发现使用迭代器取出集合中元素的代码,是一个重复的过程
所以我们可以使用循环优化
不知道集合中有多少元素,使用while循环
循环结束的条件,hasNext()方法返回false
*/
while(it.hasNext()){
String s = it.next();
System.out.println(s);
}
System.out.println("---------");
for(Iterator<String> it2=coll.iterator();it2.hasNext();){
String s = it2.next();
System.out.println(s);
}
/*
2.使用Iterator接口中的方法hasNext()判断还有没有下一个元素
*/
// boolean b = it.hasNext();
// System.out.println(b);
//3.使用Iterator接口中的方法next取出集合中的下一个元素
// String next = it.next();
// System.out.println(next);
//
// b = it.hasNext();
// System.out.println(b);
// next = it.next();
// System.out.println(next);
//
//
// b = it.hasNext();
// System.out.println(b);
// next = it.next();
// System.out.println(next);
//
// next = it.next();
// System.out.println(next);
//
//
// b = it.hasNext();
// System.out.println(b);
// next = it.next();
// System.out.println(next);
//
//
// b = it.hasNext();
// System.out.println(b);
}
}
迭代器---Iterator
最新推荐文章于 2022-04-18 19:15:46 发布