001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkState;
020
021import com.google.common.annotations.GwtCompatible;
022
023import java.util.NoSuchElementException;
024
025/**
026 * This class provides a skeletal implementation of the {@code Iterator}
027 * interface, to make this interface easier to implement for certain types of
028 * data sources.
029 *
030 * <p>{@code Iterator} requires its implementations to support querying the
031 * end-of-data status without changing the iterator's state, using the {@link
032 * #hasNext} method. But many data sources, such as {@link
033 * java.io.Reader#read()}, do not expose this information; the only way to
034 * discover whether there is any data left is by trying to retrieve it. These
035 * types of data sources are ordinarily difficult to write iterators for. But
036 * using this class, one must implement only the {@link #computeNext} method,
037 * and invoke the {@link #endOfData} method when appropriate.
038 *
039 * <p>Another example is an iterator that skips over null elements in a backing
040 * iterator. This could be implemented as: <pre>   {@code
041 *
042 *   public static Iterator<String> skipNulls(final Iterator<String> in) {
043 *     return new AbstractIterator<String>() {
044 *       protected String computeNext() {
045 *         while (in.hasNext()) {
046 *           String s = in.next();
047 *           if (s != null) {
048 *             return s;
049 *           }
050 *         }
051 *         return endOfData();
052 *       }
053 *     };
054 *   }}</pre>
055 *
056 * <p>This class supports iterators that include null elements.
057 *
058 * @author Kevin Bourrillion
059 * @since 2.0
060 */
061// When making changes to this class, please also update the copy at
062// com.google.common.base.AbstractIterator
063@GwtCompatible
064public abstract class AbstractIterator<T> extends UnmodifiableIterator<T> {
065  private State state = State.NOT_READY;
066
067  /** Constructor for use by subclasses. */
068  protected AbstractIterator() {}
069
070  private enum State {
071    /** We have computed the next element and haven't returned it yet. */
072    READY,
073
074    /** We haven't yet computed or have already returned the element. */
075    NOT_READY,
076
077    /** We have reached the end of the data and are finished. */
078    DONE,
079
080    /** We've suffered an exception and are kaput. */
081    FAILED,
082  }
083
084  private T next;
085
086  /**
087   * Returns the next element. <b>Note:</b> the implementation must call {@link
088   * #endOfData()} when there are no elements left in the iteration. Failure to
089   * do so could result in an infinite loop.
090   *
091   * <p>The initial invocation of {@link #hasNext()} or {@link #next()} calls
092   * this method, as does the first invocation of {@code hasNext} or {@code
093   * next} following each successful call to {@code next}. Once the
094   * implementation either invokes {@code endOfData} or throws an exception,
095   * {@code computeNext} is guaranteed to never be called again.
096   *
097   * <p>If this method throws an exception, it will propagate outward to the
098   * {@code hasNext} or {@code next} invocation that invoked this method. Any
099   * further attempts to use the iterator will result in an {@link
100   * IllegalStateException}.
101   *
102   * <p>The implementation of this method may not invoke the {@code hasNext},
103   * {@code next}, or {@link #peek()} methods on this instance; if it does, an
104   * {@code IllegalStateException} will result.
105   *
106   * @return the next element if there was one. If {@code endOfData} was called
107   *     during execution, the return value will be ignored.
108   * @throws RuntimeException if any unrecoverable error happens. This exception
109   *     will propagate outward to the {@code hasNext()}, {@code next()}, or
110   *     {@code peek()} invocation that invoked this method. Any further
111   *     attempts to use the iterator will result in an
112   *     {@link IllegalStateException}.
113   */
114  protected abstract T computeNext();
115
116  /**
117   * Implementations of {@link #computeNext} <b>must</b> invoke this method when
118   * there are no elements left in the iteration.
119   *
120   * @return {@code null}; a convenience so your {@code computeNext}
121   *     implementation can use the simple statement {@code return endOfData();}
122   */
123  protected final T endOfData() {
124    state = State.DONE;
125    return null;
126  }
127
128  @Override
129  public final boolean hasNext() {
130    checkState(state != State.FAILED);
131    switch (state) {
132      case DONE:
133        return false;
134      case READY:
135        return true;
136      default:
137    }
138    return tryToComputeNext();
139  }
140
141  private boolean tryToComputeNext() {
142    state = State.FAILED; // temporary pessimism
143    next = computeNext();
144    if (state != State.DONE) {
145      state = State.READY;
146      return true;
147    }
148    return false;
149  }
150
151  @Override
152  public final T next() {
153    if (!hasNext()) {
154      throw new NoSuchElementException();
155    }
156    state = State.NOT_READY;
157    T result = next;
158    next = null;
159    return result;
160  }
161
162  /**
163   * Returns the next element in the iteration without advancing the iteration,
164   * according to the contract of {@link PeekingIterator#peek()}.
165   *
166   * <p>Implementations of {@code AbstractIterator} that wish to expose this
167   * functionality should implement {@code PeekingIterator}.
168   */
169  public final T peek() {
170    if (!hasNext()) {
171      throw new NoSuchElementException();
172    }
173    return next;
174  }
175}