I’ve written my own linked-list type data structure, and would like to create an Iterator object that allows me to iterate over the nodes in the list.
Is it possible to directly define my own iterator, or would I first need to convert it to an existing data structure like LinkedList and call iterator() on that?
You can define your own Iterator class by implementing the three methods of the Iterator interface:
The last method is optional: you can implement it to just throw an UnsupportedOperationException.
The most common strategy is to make the actual class a private member class of your list class. That way it has access to the private bookkeeping data of your class; this is often required to implement an efficient iterator.
Once you do implement an iterator class, it’s usually helpful to have the list class implement Iterable. That gives client code a way to obtain an iterator.