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.Beta;
020import com.google.common.annotations.GwtCompatible;
021
022import java.util.NoSuchElementException;
023
024import javax.annotation.Nullable;
025
026/**
027 * This class provides a skeletal implementation of the {@code Iterator}
028 * interface for sequences whose next element can always be derived from the
029 * previous element. Null elements are not supported, nor is the
030 * {@link #remove()} method.
031 *
032 * <p>Example: <pre>   {@code
033 *
034 *   Iterator<Integer> powersOfTwo = new AbstractLinkedIterator<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 8.0
042 * @deprecated This class has been renamed {@link AbstractSequentialIterator}.
043 *     This class is scheduled to be removed in Guava release 13.0.
044 */
045@Beta
046@Deprecated
047@GwtCompatible
048public abstract class AbstractLinkedIterator<T>
049    extends UnmodifiableIterator<T> {
050  private T nextOrNull;
051
052  /**
053   * Creates a new iterator with the given first element, or, if {@code
054   * firstOrNull} is null, creates a new empty iterator.
055   */
056  protected AbstractLinkedIterator(@Nullable T firstOrNull) {
057    this.nextOrNull = firstOrNull;
058  }
059
060  /**
061   * Returns the element that follows {@code previous}, or returns {@code null}
062   * if no elements remain. This method is invoked during each call to
063   * {@link #next()} in order to compute the result of a <i>future</i> call to
064   * {@code next()}.
065   */
066  protected abstract T computeNext(T previous);
067
068  @Override
069  public final boolean hasNext() {
070    return nextOrNull != null;
071  }
072
073  @Override
074  public final T next() {
075    if (!hasNext()) {
076      throw new NoSuchElementException();
077    }
078    try {
079      return nextOrNull;
080    } finally {
081      nextOrNull = computeNext(nextOrNull);
082    }
083  }
084}