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