1.迭代器的基本使用
public class Demo07 {
public static void main(String[] args) {
List<Student> arr = new ArrayList<>();
Student s1 = new Student("zhangsan",11);
Student s2 = new Student("lisi",12);
Student s3 = new Student("wangwu",13);
arr.add(s1);
arr.add(s2);
arr.add(s3);
Iterator<Student> iterator = arr.iterator();
while (true){
if(iterator.hasNext()){
Student student = iterator.next();
System.out.println(student);
}else {
System.out.println("结束");
break;
}
}
}
}
Student{name='zhangsan', age=11}
Student{name='lisi', age=12}
Student{name='wangwu', age=13}
结束
注意:对于集合使用迭代器进行遍历,只有继承或者实现了Iterable<T>接口才可以使用迭代器进行遍历,在集合中,单列集合Collection<T>继承了Iterable<E>接口,而双列集合Map<K,V>并没有,也就是说双列集合不能使用迭代器进行遍历.
2.迭代器的底层原理
创建迭代器对象:当创建迭代器后,迭代器的游标会默认指向集合的0索引;
iterator.hasNext():判断当前游标是否存在元素,返回true或false;
iterator.next():获取当前元素并将游标移向下一个索引