iterator迭代器
Iterator迭代器
因为各个集合的存取方式不同,所以出现了迭代器,是Collection集合元素的通用获取方式。
使用
hasNext()如果仍有元素可以叠戴,返回true
next()返回迭代的下一个元素
步骤
- 使用Collection中方法iterator()获取迭代器的实现类对象,使用Iterator接口接受(多态)
- 使用hasNext()判断
- 使用next()取出
用while或用for循环都可以
代码:
public class Main {
Collection<Integer> c;
public Main() {
c = new ArrayList<>();
c.add(1);
c.add(2);
c.add(3);
}
public void output1(){
System.out.println("while输出");
Iterator<Integer> it = c.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
}
public void output2(){
System.out.println("for输出");
for(Iterator<Integer>it = c.iterator();it.hasNext();){
System.out.println(it.next());
}
}
public static void main(String[] args) {
Main m = new Main();
m.output1();
m.output2();
}
}
实现原理:
c.iterator():获取迭代器的实现类对象,并且把指针指向集合的-1索引
增强for循环
for(集合/数组的数据类型 变量名:数组名/集合名){
sout(变量名);
}