java iterator 遍历状态模式通过封装迭代器的内部状态(如当前索引、是否越界)来管理遍历过程,核心做法是实现 iterator 接口并维护一个指向当前元素的指针。具体实现时,需定义 hasnext() 和 next() 方法,在 next() 中更新状态并返回元素,同时处理边界条件以防止 concurrentmodificationexception 或越界异常。这样做能确保遍历逻辑与集合结构解耦,提供统一的访问接口。

Iterator 接口如何定义状态转换规则
Iterator 接口定义了 hasNext() 和 next() 两个核心方法,用于控制遍历的状态转换。当 hasNext() 返回 true 时,表示存在下一个元素,调用 next() 会推进状态并返回当前元素;若返回 false,则遍历结束。这种设计将“是否继续”的判断与“获取元素”的动作分离,使状态机清晰可控。

import java.util.Iterator;
import java.util.List;
public class CustomIterator<T> implements Iterator<T> {
private List<T> list;
private int index = 0;
public CustomIterator(List<T> list) {
this.list = list;
}
@Override
public boolean hasNext() {
return index < list.size();
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return list.get(index++);
}
}预期结果:对于包含 [A, B, C] 的列表,hasNext() 依次返回 true, true, true, false;next() 依次返回 A, B, C,第四次调用抛出异常。
立即学习“Java免费学习笔记(深入)”;
如何避免遍历时修改集合导致的并发异常
为避免 ConcurrentModificationException,应在迭代器中记录集合的结构修改次数(modCount),并在每次调用 next() 时校验该值。若发现不一致,说明集合被外部修改,立即抛出异常。这种做法保证了快速失败(fail-fast)机制,确保遍历过程中的数据一致性。

import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class SafeIterator<T> implements Iterator<T> {
private List<T> list;
private int index = 0;
private int expectedModCount;
public SafeIterator(List<T> list) {
this.list = list;
this.expectedModCount = list.size(); // 简化模拟 modCount
}
@Override
public boolean hasNext() {
return index < list.size();
}
@Override
public T next() {
if (list.size() != expectedModCount) {
throw new ConcurrentModificationException();
}
if (!hasNext()) {
throw new NoSuchElementException();
}
return list.get(index++);
}
}预期结果:若在迭代过程中调用 list.add(),next() 将抛出 ConcurrentModificationException;否则正常遍历。
当集合为空时 Iterator 的行为是什么
当集合为空时,hasNext() 直接返回 false,next() 不会执行任何操作,而是抛出 NoSuchElementException。这是因为初始索引为 0,而集合大小为 0,hasNext() 判断为假,导致 next() 进入异常分支。这种行为符合 Java 标准库的设计规范,确保空集合遍历的安全性与一致性。


















