java迭代器设计模式通过iterator接口封装遍历逻辑,使客户端无需关心集合内部结构;iterable接口定义iterator()方法,iterator提供hasnext()和next(),arraylist等集合默认实现,自定义intarray可支持for-each循环,需注意fail-fast机制、状态隔离与remove同步。

Java 中的迭代器设计模式通过 Iterator 接口和配套实现类来封装集合内部遍历逻辑,让客户端无需关心数据结构细节即可统一访问元素。
核心接口与约定
Java 标准库已提供规范化的支持:
-
Iterable<t></t>接口定义iterator()方法,表示“可被遍历” -
Iterator<t></t>接口提供hasNext()和next(),控制遍历流程 - 集合类(如
ArrayList、LinkedList)默认实现Iterable,返回具体迭代器实例
手写一个自定义迭代器
假设你有一个简单数组容器 IntArray,想支持 for-each 循环:
public class IntArray implements Iterable<integer> {
private final int[] data;
public IntArray(int... values) {
this.data = values;
}
@Override
public Iterator<integer> iterator() {
return new ArrayIterator();
}
private class ArrayIterator implements Iterator<integer> {
private int index = 0;
@Override
public boolean hasNext() {
return index
<p>这样就能直接使用增强 for 循环:<br><code>for (int x : new IntArray(1, 2, 3)) { System.out.println(x); }</code></p>
<h3>注意迭代器的安全性与状态管理</h3>
<p>真实项目中需关注几个关键点:</p>
<ul>
<li>迭代器应是“快照式”或“fail-fast”:多数 JDK 集合的迭代器在检测到并发修改时抛 <code>ConcurrentModificationException</code>
</li>
<li>避免在遍历中修改原集合(除非用 <code>Iterator.remove()</code>)</li>
<li>每次调用 <code>iterator()</code> 应返回新实例,保证多个迭代器互不干扰</li>
<li>如果集合支持修改,迭代器的 <code>remove()</code> 方法需同步更新底层结构</li>
</ul>
<h3>扩展:支持双向遍历(ListIterator)</h3>
<p>当需要前后移动或定位插入位置时,可用 <code>ListIterator</code>:</p>
<ul>
<li>继承 <code>Iterator</code>,增加 <code>hasPrevious()</code>、<code>previous()</code>、<code>nextIndex()</code> 等方法</li>
<li>
<code>ArrayList.listIterator()</code> 就是典型实现,支持从任意索引开始双向遍历</li>
<li>自定义实现时需维护两个方向的游标(如 <code>nextIndex</code> 和 <code>previousIndex</code>)</li>
</ul></integer></integer></integer>Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











