A cyclic iterator

Sometimes, a cyclic iterator can be useful to supply an endless supply of deterministic data. Here’s an simple implementation that I wrote today.


import java.util.Iterator;

/**
 * This class iterates across an iterable object with the option to recycle amongst the elements infinitely.
 * In case the recycle option is not set, the original data is iterated upon once, and all subsequent calls to
 * next() will return the defaultDataValue
 *
 * @param <T>
 */
public class CyclicIterator<T>
 implements Iterator<T> {
 final private Iterable<T> data;
 final private boolean recycleData;
 final private T defaultDataValue;
 private Iterator<T> dataIterator;

public CyclicIterator(Iterable<T> data, boolean recycle, T defaultDataValue) {
 this.data = data;
 this.recycleData = recycle;
 this.defaultDataValue = defaultDataValue;
 resetDataIterator();
 }

private void resetDataIterator() {
 this.dataIterator = this.data.iterator();
 }

@Override
 public boolean hasNext() {
 return true;
 }

@Override
 public T next() {
 //if the iterator is done, check whether to reset or not
 if (!dataIterator.hasNext()) {
 if (recycleData) {
 resetDataIterator();
 } else {
 return defaultDataValue;
 }
 }

//at this point, next should be valid
 return dataIterator.next();
 }

@Override
 public void remove() {
 //NO-OP
 }
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s