PreIndexedContentIterator.java

  1. package no.motif.iter;

  2. /**
  3.  * Base implementation for iterating over elements retrieved using an
  4.  * incrementing index, where the start and end indexes are known beforehand.
  5.  * E.g. characters of a String, or elements of an array.
  6.  */
  7. public abstract class PreIndexedContentIterator<T> extends ReadOnlyIterator<T> {

  8.     private final int endIndex;
  9.     private int next;

  10.     /**
  11.      * @param endIndex The end index, exclusively.
  12.      */
  13.     public PreIndexedContentIterator(int endIndex) {
  14.         this(0, endIndex);
  15.     }

  16.     /**
  17.      * @param startIndex The first index, inclusively
  18.      * @param endIndex The end index, exclusively.
  19.      */
  20.     public PreIndexedContentIterator(int startIndex, int endIndex) {
  21.         if (endIndex < startIndex) throw new IllegalArgumentException(
  22.             "endIndex must be same or more than startIndex. startIndex=" + startIndex + ", endIndex=" + endIndex);
  23.         this.next = startIndex;
  24.         this.endIndex = endIndex;
  25.     }

  26.     @Override
  27.     public final boolean hasNext() {
  28.         return next < endIndex;
  29.     }

  30.     @Override
  31.     public final T next() {
  32.         if (hasNext()) return elementAt(next++);
  33.         else throw new IndexOutOfBoundsException(String.valueOf(next));
  34.     }

  35.     /**
  36.      *
  37.      * @param index The index of the element to yield. Guarantied to never
  38.      *              be out of bounds with respect to the start and end indexes.
  39.      *              E.g. if the given start and end indexes are 0 and 4, this
  40.      *              method will be called for each of the indexes 0, 1, 2, and 3.
  41.      *
  42.      * @return The element for the given index.
  43.      */
  44.     protected abstract T elementAt(int index);
  45. }