Class AbstractIterator<E>
- Type Parameters:
E- the type of elements returned by this iterator - 迭代器返回的元素类型
- All Implemented Interfaces:
Iterator<E>
Provides a simplified way to write an Iterator. Subclasses need only
implement computeNext() and call endOfData() when iteration is complete.
提供了一种简化的方式来编写 Iterator。子类只需实现 computeNext(),
并在迭代结束时调用 endOfData()。
Features | 主要功能:
- Lazy element computation - 延迟计算元素
- Supports null elements - 支持 null 元素
- peek() to inspect next element without consuming - peek() 查看下一个元素但不消费
- Fail-safe state machine prevents misuse - 安全的状态机防止误用
Usage Examples | 使用示例:
// Iterate over an array range - 迭代数组范围
Iterator<String> iter = new AbstractIterator<>() {
private int index = 0;
private final String[] data = {"a", "b", "c"};
@Override
protected String computeNext() {
return index < data.length ? data[index++] : endOfData();
}
};
while (iter.hasNext()) {
System.out.println(iter.next());
}
Performance | 性能特性:
- Time complexity: O(1) per hasNext/next call - 时间复杂度: 每次 hasNext/next 调用 O(1)
- Space complexity: O(1) overhead - 空间复杂度: O(1) 额外开销
Security | 安全性:
- Thread-safe: No - 线程安全: 否
- Null elements: Supported - 空元素: 支持
- Since:
- JDK 25, opencode-base-collections V1.0.3
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Constructor Details
-
AbstractIterator
public AbstractIterator()
-
-
Method Details
-
computeNext
Computes the next element in the iteration. 计算迭代中的下一个元素。Implementations must return the next element, or call
endOfData()and return its result when there are no more elements.实现必须返回下一个元素,或者在没有更多元素时调用
endOfData()并返回其结果。- Returns:
- the next element, or the result of
endOfData()下一个元素,或endOfData()的结果
-
endOfData
Signals that the iteration is complete. 通知迭代已完成。Call this method from
computeNext()when there are no more elements. Always return the result of this method from computeNext().当没有更多元素时,从
computeNext()调用此方法。 始终从 computeNext() 返回此方法的结果。- Returns:
- always
null- 始终返回null
-
hasNext
public final boolean hasNext()Multiple calls to this method are idempotent; the underlying
computeNext()is invoked at most once per element.对此方法的多次调用是幂等的;底层的
computeNext()每个元素最多调用一次。 -
next
- Specified by:
nextin interfaceIterator<E>- Throws:
NoSuchElementException- if iteration has no more elements 如果迭代没有更多元素
-
peek
Returns the next element without advancing the iterator. 返回下一个元素但不推进迭代器。Subsequent calls to
peek()return the same element untilnext()is called.在调用
next()之前,对peek()的后续调用返回相同的元素。- Returns:
- the next element - 下一个元素
- Throws:
NoSuchElementException- if iteration has no more elements 如果迭代没有更多元素
-