使用迭代器模式解耦遍历逻辑的核心做法是定义一个统一的 iterator 接口,让集合类实现该接口并返回具体的迭代器实例。这样调用方只需通过 hasnext() 和 next() 方法即可安全地遍历容器内部元素,无需关心底层数据结构(如数组、链表或树)的具体存储方式。这种设计将“如何遍历”的责任从客户端转移到了迭代器对象中,实现了访问逻辑与数据结构的分离。

Java Iterator 接口包含哪些核心方法
Java 中的 Iterator 接口主要包含三个核心方法:boolean hasNext() 用于判断是否还有下一个元素,E next() 用于获取当前元素并将指针后移,以及 void remove() 用于移除迭代器返回的最后一个元素。这些方法构成了遍历的标准契约,确保无论底层结构如何变化,外部代码都能以统一的方式访问数据。

import java.util.Iterator;
// 自定义集合接口
interface MyCollection {
void add(String item);
Iterator<String> iterator();
}
// 具体集合实现:基于数组
public class ArrayCollection implements MyCollection {
private String[] items = new String[10];
private int size = 0;
public void add(String item) {
if (size < items.length) {
items[size++] = item;
}
}
// 返回具体的迭代器实例
@Override
public Iterator<String> iterator() {
return new ArrayIterator();
}
// 内部类实现迭代器逻辑
private class ArrayIterator implements Iterator<String> {
private int currentIndex = 0;
@Override
public boolean hasNext() {
return currentIndex < size;
}
@Override
public String next() {
if (!hasNext()) {
throw new java.util.NoSuchElementException();
}
return items[currentIndex++];
}
@Override
public void remove() {
if (currentIndex == 0) {
throw new IllegalStateException("No element to remove");
}
// 简单移除:将后续元素前移
System.arraycopy(items, currentIndex, items, currentIndex - 1, size - currentIndex);
size--;
currentIndex--;
}
}
public static void main(String[] args) {
MyCollection collection = new ArrayCollection();
collection.add("Apple");
collection.add("Banana");
collection.add("Cherry");
// 客户端代码只依赖 Iterator 接口
Iterator<String> it = collection.iterator();
while (it.hasNext()) {
String item = it.next();
System.out.println(item);
if ("Banana".equals(item)) {
it.remove(); // 安全移除
}
}
}
}
为什么需要自定义迭代器而不是直接暴露集合内部状态
直接暴露集合内部状态(如公开数组索引或节点指针)会导致客户端代码与集合实现细节强耦合,且容易破坏封装性。通过自定义迭代器,可以将遍历过程中的状态(如当前索引、当前节点引用)封装在迭代器对象内部。这样不仅保证了线程安全性(每个迭代器拥有独立状态),还允许我们在遍历时动态修改集合结构(如通过 remove() 方法),而不会导致并发修改异常或索引越界。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
立即学习“Java免费学习笔记(深入)”;

import java.util.Iterator;
// 链表节点
class Node {
String data;
Node next;
Node(String data) { this.data = data; }
}
// 链表集合
public class LinkedListCollection implements MyCollection {
private Node head = null;
private int size = 0;
public void add(String item) {
Node newNode = new Node(item);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
size++;
}
@Override
public Iterator<String> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<String> {
private Node current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public String next() {
if (!hasNext()) {
throw new java.util.NoSuchElementException();
}
String data = current.data;
current = current.next;
return data;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Remove not supported in this simple example");
}
}
public static void main(String[] args) {
MyCollection collection = new LinkedListCollection();
collection.add("Dog");
collection.add("Cat");
collection.add("Bird");
Iterator<String> it = collection.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
当集合为空时 Iterator 的行为表现是什么
当集合为空时,hasNext() 方法会立即返回 false,而 next() 方法如果在此时被调用,会抛出 java.util.NoSuchElementException。这是 Java 迭代器模式的约定行为,旨在提醒调用者检查是否有可用元素。在实际开发中,应避免在未检查 hasNext() 的情况下直接调用 next(),以防止程序崩溃。对于空集合,迭代器对象本身仍然有效,只是其内部状态指向无效位置或初始位置,确保多次调用 hasNext() 始终返回 false。

















