JavaSE-14.1.3【迭代器Iterator、Collection集合的遍历】

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package day5.lesson1;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
 
/*
1.4 Collection集合的遍历
 
    迭代器Iterator
        是一个接口
        迭代器是集合的专用遍历方式
        Iterator iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
        迭代器是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的
 
    Iterator常用方法
        E next():返回迭代中的下一个元素
        boolean hasNext():若迭代具有更多元素,则返回true
 */
public class CollectionDemo3 {
    public static void main(String[] args) {
        Collection<String> collection = new ArrayList<>();
 
        collection.add("hello");
        collection.add("java");
        collection.add("world");
 
        Iterator<String> it = collection.iterator();
        //ArrayList中iterator()源码
        /*public Iterator<E> iterator() {
            return new Itr();
        }
        private class Itr implements Iterator<E> {
            ...
        }
        */
 
        /*System.out.println(it.next());
        System.out.println(it.next());
        System.out.println(it.next());
//        System.out.println(it.next()); // exception*/
 
        /*if(it.hasNext()){
            System.out.println(it.next());
        }
        if(it.hasNext()){
            System.out.println(it.next());
        }
        if(it.hasNext()){
            System.out.println(it.next());
        }
        if(it.hasNext()){
            System.out.println(it.next()); //此行未执行
        }*/
 
        while (it.hasNext()){
//            System.out.println(it.next());
            String str = it.next();
            System.out.println(str);
        }
    }
}

  

posted @   yub4by  阅读(43)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示