Implementing Iterable in a Doubly Linked List in Java
I've built a DoublyLinkedList that has all the normal methods (add(), remove(), isEmpty(), size() 开发者_如何学JAVAetc etc.)
This list holds ListNodes that have ListNode next, ListNode prev and T inf fields. (so very simple / classic here aswell)
My question is, how do I make my DLL iterable. From what I gathered I need to implement the Iterable interface, and define an iterator() method that returns an Iterator.
This is the part that I don't understand. What does that iterator() method do? How do I write it?
Any pointers appreciated. Thanks in advance PS: I know i should use the containers already available in the java packages, but I need to do it myself in this case.
The iterator()
method would return an instance of an extra class. This would keep track of what node the iterator was on, and allow you to check for the presence of more nodes (via hasNext()
) and move to the next node (via next()
).
This has to be a separate object from the list itself, as there can be multiple iterators going over the same collection at the same time. It's an extra bit of state, basically: where you are. Don't forget that the iterator starts off before the first element, logically - the first call to next()
moves to the first element.
精彩评论