Round Robin (Interleaving) Iterator of Iterators in Java
What is a round-robin iterator?
Round robin is a fairly common scheduling pattern which just refers to alternating elements one at a time over a list of inputs. So, a common question people get asked in Java and similar languages is how to implement an iterator over a sequence of iterators in a round-robin manner.
What are the pitfalls?
Iterating over all of the elements in a list of iterators fairly is relatively straight-forward to grasp, but it gets a little complicated when you try to implement it. The three biggest things to watch out for are:
- Making next() and hasNext() work together - hasNext() must be able to locate the next element to know one exists, and next() should defer to hasNext() to ensure that a next element does exist before trying to return one.
- Ensuring that you correctly reset the iterator which moves over the sub-list iterators each time it reaches the end of the iterator list. You will move over the list of iterators many times as you are only taking one item from each sub-list on each pass.
- Remove sub-lists using the Iterator.remove() method once you determine they have no elements left. This lets you track your "finished" condition easily; you are finished once no iterators remain in your list of iterators.
Read full article from Round Robin (Interleaving) Iterator of Iterators in Java
No comments:
Post a Comment