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