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

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

Go to download

a-base is a library of basic (hence the name) classes, most notably immutable collection classes with copy-on-write operations

The newest version!
package com.ajjpj.abase.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() {
        while(!curIterator.hasNext() && itit.hasNext()) {
            curIterator = itit.next();
        }

        return curIterator.hasNext();
    }

    @Override
    public T next() {
        return curIterator.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();
        }
    };
}