001/*
002 * Copyright (C) 2010 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 com.google.common.annotations.GwtCompatible;
020import java.util.NoSuchElementException;
021import javax.annotation.CheckForNull;
022
023/**
024 * This class provides a skeletal implementation of the {@code Iterator} interface for sequences
025 * whose next element can always be derived from the previous element. Null elements are not
026 * supported, nor is the {@link #remove()} method.
027 *
028 * <p>Example:
029 *
030 * <pre>{@code
031 * Iterator<Integer> powersOfTwo =
032 *     new AbstractSequentialIterator<Integer>(1) {
033 *       protected Integer computeNext(Integer previous) {
034 *         return (previous == 1 << 30) ? null : previous * 2;
035 *       }
036 *     };
037 * }</pre>
038 *
039 * @author Chris Povirk
040 * @since 12.0 (in Guava as {@code AbstractLinkedIterator} since 8.0)
041 */
042@GwtCompatible
043@ElementTypesAreNonnullByDefault
044public abstract class AbstractSequentialIterator<T> extends UnmodifiableIterator<T> {
045  @CheckForNull private T nextOrNull;
046
047  /**
048   * Creates a new iterator with the given first element, or, if {@code firstOrNull} is null,
049   * creates a new empty iterator.
050   */
051  protected AbstractSequentialIterator(@CheckForNull T firstOrNull) {
052    this.nextOrNull = firstOrNull;
053  }
054
055  /**
056   * Returns the element that follows {@code previous}, or returns {@code null} if no elements
057   * remain. This method is invoked during each call to {@link #next()} in order to compute the
058   * result of a <i>future</i> call to {@code next()}.
059   */
060  @CheckForNull
061  protected abstract T computeNext(T previous);
062
063  @Override
064  public final boolean hasNext() {
065    return nextOrNull != null;
066  }
067
068  @Override
069  public final T next() {
070    if (nextOrNull == null) {
071      throw new NoSuchElementException();
072    }
073    T oldNext = nextOrNull;
074    nextOrNull = computeNext(oldNext);
075    return oldNext;
076  }
077}