SingularIterator.java

  1. package no.motif.iter;

  2. import java.util.NoSuchElementException;

  3. /**
  4.  * Wraps a single object in an iterator. The object is returned at most
  5.  * once from {@link #next()}.
  6.  */
  7. public final class SingularIterator<V> extends ReadOnlyIterator<V> {

  8.     private final V value;
  9.     private boolean hasBeenReturned = false;

  10.     public SingularIterator(V value) {
  11.         this.value = value;
  12.     }

  13.     @Override
  14.     public boolean hasNext() {
  15.         return !hasBeenReturned;
  16.     }

  17.     @Override
  18.     public V next() {
  19.         if (hasBeenReturned) throw new NoSuchElementException();
  20.         hasBeenReturned = true;
  21.         return value;
  22.     }

  23. }