迭代器的基本使用及底层原理

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():获取当前元素并将游标移向下一个索引

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值