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

ch.lambdaj.util.iterator.ResettableIteratorOnIterator Maven / Gradle / Ivy

There is a newer version: 2.3.3
Show newest version
// Modified or written by Ex Machina SAGL for inclusion with lambdaj.
// Copyright (c) 2009 Mario Fusco.
// Licensed under the Apache License, Version 2.0 (the "License")

package ch.lambdaj.util.iterator;

import java.util.*;

/**
 * A ResettabkeIterator that iterates over a wrapped Iterator
 * @author Mario Fusco
 */
public class ResettableIteratorOnIterator extends ResettableIterator {

    private final Iterator iterator;

    private final List innerIterable = new LinkedList();
    private Iterator innerIterator;

    private final List cache = new LinkedList();

    /**
     * Creates a ResettableIterator that wraps the given Iterator
     * @param iterator The Iterator to be wrapped
     */
    public ResettableIteratorOnIterator(Iterator iterator) {
        this.iterator = iterator;
        innerIterator = innerIterable.iterator();
    }

    /**
     * {@inheritDoc}
     */
    public void reset() {
        innerIterable.addAll(cache);
        cache.clear();
        innerIterator = innerIterable.iterator();
    }

    /**
     * {@inheritDoc}
     */
    public boolean hasNext() {
        return iterator.hasNext() || innerIterator.hasNext();
    }

    /**
     * {@inheritDoc}
     */
    public T next() {
        if (innerIterator.hasNext()) return innerIterator.next();
        if (iterator.hasNext()) {
            T next = iterator.next();
            cache.add(next);
            return next;
        }
        throw new NoSuchElementException();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy