Use a LoopingIterator
to repeatedly iterate through the contents of a Collection
. Pass an existing Collection
to the constructor of LoopingIterator
, and call iterator( )
. The
following code uses a LoopingIterator
to retrieve five items from a List
with three items:
List drivers = new ArrayList( ); drivers.add( "Chris" ); drivers.add( "Sean" ); drivers.add( "Kathy" ); LoopingIterator loopingIterator = new LoopingIterator( drivers ); for( int i = 1; i <= 5; i++ ) { String driver = (String) loopingIterator.next( ); System.out.println( "Driver for Day " + i + ": " + driver ); }
The previous example simulates the selection of a driver in a car
pool with three drivers. Five drivers are selected, and the LoopingIterator
returns the first item in the
List
on the fourth day:
Driver for Day 1: Chris Driver for Day 2: Sean Driver for Day 3: Kathy Driver for Day 4: Chris Driver for Day 5: Sean
Keep in mind that a LoopingIterator
never stops iterating;
hasNext( )
always returns true
in
a LoopingIterator
. If you are using a
LoopingIterator
with a while
loop, be sure to code an exit condition.
A LoopingIterator
is appropriate for
a situation in which a series of values must be repeatedly evaluated, or
a loop of commands must be repeatedly executed. An application, for
example, may have a series of components that need to be continuously
updated, or a series of queues or buffers that need to be continuously
tested or monitored—an event loop, for example.
The LoopingIterator
also
implements the Commons Collections interface ResettableIterator
; this extension of the
Iterator
interface can be reset to
start at the beginning of a Collection
. When using a ResettableIterator
, call reset()
to jump back to the beginning of a
Collection
:
List items = new ArrayList( ); items.add( "Item 1" ); items.add( "Item 2" ); items.add( "Item 3" ); LoopingIterator iterator = new LoopingIterator( items ); // Print out two elements from the LoopingIterator System.out.println( iterator.next( ) ); System.out.println( iterator.next( ) ); // Reset iterator to start of List System.out.println( "Reset" ); iterator.reset( ); // Print out two elements from the LoopingIterator System.out.println( iterator.next( ) ); System.out.println( iterator.next( ) );
This example iterates over the first two elements in a List
before calling reset( )
. After calling reset( )
, the code calls next( )
twice, printing out the first two
elements, as shown below:
Item 1 Item 2 Reset Item 1 Item 2
Recipe
5.3 deals with another implementation of ResettableIterator
, ArrayListIterator
, which can be used to
iterate over a subset of elements in an ArrayList
.