Implementing a Custom Iterator
Build a custom iterator class for a simple linked list or range structure.
Custom Iterator
Building a custom iterator gives you full control over how a data structure is traversed. This lesson walks through implementing a linked-list iterator step by step.
The Node Class
First, define the node structure for a singly-linked list.
class Node<T> {
final T value;
Node<T> next;
Node(T value) {
this.value = value;
}
}
// Building a chain: 1 -> 2 -> 3
Node<Integer> head = new Node<>(1);
head.next = new Node<>(2);
head.next.next = new Node<>(3);All lessons in this course
- The Iterable and Iterator Contracts
- Implementing a Custom Iterator
- ListIterator and Bidirectional Traversal
- Fail-Fast vs Fail-Safe Iterators