All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.staccatocommons.iterators.PrependThriterator Maven / Gradle / Ivy

There is a newer version: 2.3
Show newest version
/**
 *  Copyright (c) 2010-2012, The StaccatoCommons Team
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation; version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 */


package net.sf.staccatocommons.iterators;

import java.util.Iterator;
import java.util.NoSuchElementException;

import net.sf.staccatocommons.defs.Thunk;
import net.sf.staccatocommons.iterators.thriter.AdvanceThriterator;
import net.sf.staccatocommons.iterators.thriter.Thriter;
import net.sf.staccatocommons.iterators.thriter.Thriterator;
import net.sf.staccatocommons.iterators.thriter.Thriterators;
import net.sf.staccatocommons.iterators.thriter.internal.ConstantThunk;

/**
 * @author flbulgarelli
 * 
 */
public class PrependThriterator extends AdvanceThriterator {

  private final A element;
  private final Thriter iter;
  private boolean elementConsumed;
  private boolean iterAdvanced;

  /**
   * Creates a new {@link PrependThriterator}
   */
  public PrependThriterator(A element, Thriter iterator) {
    this.element = element;
    this.iter = iterator;
  }

  /**
   * Creates a new {@link PrependThriterator}
   */
  public PrependThriterator(A element, Iterator iterator) {
    this(element, (Thriter) Thriterators.from(iterator));
  }

  /**
   * Creates a new {@link PrependThriterator}
   */
  public PrependThriterator(A element, Thriterator iterator) {
    this(element, (Thriter) iterator);
  }

  public final boolean hasNext() {
    return !elementConsumed || iter.hasNext();
  }

  public final void advanceNext() throws NoSuchElementException {
    if (!elementConsumed) {
      elementConsumed = true;
    } else {
      iter.advanceNext();
      iterAdvanced = true;
    }
  }

  public final A current() throws NoSuchElementException {
    if (iterAdvanced)
      return iter.current();
    return elementValue();
  }

  protected A elementValue() {
    return element;
  }

  protected Thunk elementThunk() {
    return new ConstantThunk(element);
  }

  public Thunk delayedCurrent() {
    if (iterAdvanced)
      return (Thunk) iter.delayedCurrent();
    return elementThunk();
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy