Ierator迭代器

在Java中遍历List时会用到Java提供的Iterator,且十分好用,原因:

迭代器是一种设计模式,它是一个对象,它可以遍历并选择序列中的对象,而开发人员不需要了解该序列的底层结构。迭代器通常被称为“轻量级”对象,因为创建它的代价小。

Java中的Iterator功能比较简单,并且只能单向移动

(1) 使用方法iterator()要求容器返回一个Iterator。第一次调用Iterator的next()方法时,它返回序列的第一个元素。注意:iterator()方法是java.lang.Iterable接口,被Collection继承。

(2) 使用next()获得序列中的下一个元素。

(3) 使用hasNext()检查序列中是否还有元素。

(4) 使用remove()将迭代器新返回的元素删除。

Example:

import java.util.*;
public class Muster {
 
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add("a");
        list.add("b");
        list.add("c");
        Iterator it = list.iterator();
        while(it.hasNext()){
            String str = (String) it.next();
            System.out.println(str);
        }
    }
}

Result:

a
b
c

Principle

Source code(AbstractList implements Iterator):

1.    public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { // List接口实现了Collection<E>, Iterable<E> 
2.  
3.    protected AbstractList() {  
4.    }  
5.    
6.    ...  
7.  
8.    public Iterator<E> iterator() {  
9.    return new Itr();  // 这里返回一个迭代器
10.    }  
11.  
12.    private class Itr implements Iterator<E> {  // 内部类Itr实现迭代器
13.       
14.    int cursor = 0;  
15.    int lastRet = -1;  
16.    int expectedModCount = modCount;  
17.  
18.    public boolean hasNext() {  // 实现hasNext方法
19.            return cursor != size();  
20.    }  
21.  
22.    public E next() {  // 实现next方法
23.            checkForComodification();  
24.        try {  
25.        E next = get(cursor);  
26.        lastRet = cursor++;  
27.        return next;  
28.        } catch (IndexOutOfBoundsException e) {  
29.        checkForComodification();  
30.        throw new NoSuchElementException();  
31.        }  
32.    }  
33.  
34.    public void remove() {  // 实现remove方法
35.        if (lastRet == -1)  
36.        throw new IllegalStateException();  
37.            checkForComodification();  
38.  
39.        try {  
40.        AbstractList.this.remove(lastRet);  
41.        if (lastRet < cursor)  
42.            cursor--;  
43.        lastRet = -1;  
44.        expectedModCount = modCount;  
45.        } catch (IndexOutOfBoundsException e) {  
46.        throw new ConcurrentModificationException();  
47.        }  
48.    }  
49.  
50.    final void checkForComodification() {  
51.        if (modCount != expectedModCount)  
52.        throw new ConcurrentModificationException();  
53.    }  
54.    }  
55.}

实现 next()是通过get(cursor),然后cursor++,完成遍历

出处:Java中Iterator(迭代器)的用法及其背后机制的探究

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1 场景问题# 1.1 工资表数据的整合## 考虑这样一个实际应用:整合工资表数据。 这个项目的背景是这样的,项目...
    七寸知架构阅读 2,639评论 0 53
  • java笔记第一天 == 和 equals ==比较的比较的是两个变量的值是否相等,对于引用型变量表示的是两个变量...
    jmychou阅读 1,627评论 0 3
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 34,157评论 18 399
  • 在处理问题的时候,不仅仅只从自身的利益出发,还要不时地督促自己看到合作方的利益。当把双方的利益点共同进行考虑时,很...
    民哥_财富教练阅读 647评论 0 0
  • 点这里,音乐和文章更配哦~ 细数去过的古镇大概三四,听着去过的古镇大概八九,就只是听起来都一个套路,满街的古建筑里...
    邢姑娘阅读 334评论 0 0

友情链接更多精彩内容