5.2. Using a Looping Iterator

Problem

You need to loop through the contents of a Collection.

Solution

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

Discussion

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 ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.