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>
045    extends UnmodifiableIterator<T> {
046  private T nextOrNull;
047
048  /**
049   * Creates a new iterator with the given first element, or, if {@code
050   * firstOrNull} is null, creates a new empty iterator.
051   */
052  protected AbstractSequentialIterator(@Nullable T firstOrNull) {
053    this.nextOrNull = firstOrNull;
054  }
055
056  /**
057   * Returns the element that follows {@code previous}, or returns {@code null}
058   * if no elements remain. This method is invoked during each call to
059   * {@link #next()} in order to compute the result of a <i>future</i> call to
060   * {@code next()}.
061   */
062  protected abstract T computeNext(T previous);
063
064  @Override
065  public final boolean hasNext() {
066    return nextOrNull != null;
067  }
068
069  @Override
070  public final T next() {
071    if (!hasNext()) {
072      throw new NoSuchElementException();
073    }
074    try {
075      return nextOrNull;
076    } finally {
077      nextOrNull = computeNext(nextOrNull);
078    }
079  }
080}