Java Iterator核心在于集合内部私有实现类(如ArrayList.Itr),其通过cursor、lastRet和expectedModCount字段实现遍历与fail-fast机制,调用next()或remove()前校验modCount一致性,不一致则抛ConcurrentModificationException。

分析 Java Iterator 迭代器源码,关键不是直接看 Iterator 接口本身(它只有三个抽象方法),而是要结合它的**实际实现类**和**使用上下文**——因为 Iterator 是一个行为契约,真正干活的是各集合内部的私有迭代器实现,比如 ArrayList.Itr、LinkedList.ListItr 或 HashMap.KeyIterator。
从 Iterable 和 Collection 入手找入口
所有可遍历集合都实现了 Iterable 接口,而 Collection 继承自它。所以第一步是定位到具体集合类的 iterator() 方法:
-
ArrayList.iterator()返回的是内部静态类Itr -
LinkedList.iterator()返回的是ListItr(支持双向) -
HashSet.iterator()最终委托给HashMap.keySet().iterator(),走的是KeyIterator
重点看典型实现:ArrayList.Itr 源码核心逻辑
打开 ArrayList 源码(JDK 17+),找到其内部类 Itr。它维护了几个关键字段:
-
int cursor:下一个要返回元素的索引(初始为 0) -
int lastRet = -1:上一次next()返回元素的索引(-1 表示尚未调用过next) -
int expectedModCount:记录创建迭代器时集合的修改次数,用于 fail-fast 检查
hasNext() 就是简单判断 cursor != size;next() 先校验 modCount,再返回 elementData[cursor++];remove() 则删除 lastRet 对应位置的元素,并重置 lastRet。
立即学习“Java免费学习笔记(深入)”;
理解 fail-fast 机制的底层触发点
每次调用 next() 或 remove() 前,都会执行 checkForComodification():
- 对比当前集合的
modCount和迭代器保存的expectedModCount - 不一致就抛
ConcurrentModificationException - 这个
modCount在add、remove、clear等结构性修改方法中自增
调试比纯读代码更有效
在 IDE 中对如下代码打断点,单步进入 iterator() 和循环体:
Iterator
while (it.hasNext()) {
String s = it.next(); // 在这里步入
if ("b".equals(s)) it.remove();
}
观察 cursor、lastRet、modCount 的变化过程,能直观掌握指针移动、安全删除和异常触发时机。


















