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

com.ajjpj.afoundation.collection.ACompositeIterator Maven / Gradle / Ivy

There is a newer version: 1.0-pre19
Show newest version
package com.ajjpj.afoundation.collection;

import java.util.Iterator;


/**
 * This is an iterator that 'concatenates' other iterators. When it reaches the end of one of the contained iterators,
 *  it continues with the first element of the next iterator.
 *
 * @author arno
 */
public class ACompositeIterator implements Iterator {
    private final Iterator> itit;

    public ACompositeIterator(Iterator> itit) {
        this.itit = itit;
    }

    public ACompositeIterator(Iterable> itit) {
        this.itit = itit.iterator();
    }

    @SuppressWarnings("unchecked")
    private Iterator curIterator = (Iterator) EMPTY;

    @Override
    public boolean hasNext() {
        refreshCurrent ();
        return curIterator.hasNext();
    }

    @Override
    public T next() {
        refreshCurrent ();
        return curIterator.next();
    }

    private void refreshCurrent () {
        while(!curIterator.hasNext() && itit.hasNext()) {
            curIterator = itit.next();
        }
    }

    @Override
    public void remove() {
        curIterator.remove();
    }

    private static final Iterator EMPTY = new Iterator() {
        @Override
        public boolean hasNext() {
            return false;
        }

        @Override
        public Object next() {
            throw new UnsupportedOperationException();
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}