001/* Copyright (C) 2013 TU Dortmund
002 * This file is part of AutomataLib, http://www.automatalib.net/.
003 * 
004 * AutomataLib is free software; you can redistribute it and/or
005 * modify it under the terms of the GNU Lesser General Public
006 * License version 3.0 as published by the Free Software Foundation.
007 * 
008 * AutomataLib is distributed in the hope that it will be useful,
009 * but WITHOUT ANY WARRANTY; without even the implied warranty of
010 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
011 * Lesser General Public License for more details.
012 * 
013 * You should have received a copy of the GNU Lesser General Public
014 * License along with AutomataLib; if not, see
015 * http://www.gnu.de/documents/lgpl.en.html.
016 */
017package net.automatalib.commons.util.collections;
018
019import java.util.Iterator;
020import java.util.NoSuchElementException;
021
022public class ConcatIterator<T> implements Iterator<T> {
023        
024        private final Iterator<? extends T>[] iterators;
025        private int currentIndex;
026        
027        @SafeVarargs
028        public ConcatIterator(Iterator<? extends T> ...iterators) {
029                int numIts = iterators.length;
030                int i = 0;
031                while(i < numIts) {
032                        Iterator<? extends T> it = iterators[i];
033                        if(it.hasNext())
034                                break;
035                        i++;
036                }
037                if(i == numIts) {
038                        this.iterators = null;
039                        this.currentIndex = -1;
040                }
041                else {
042                        this.iterators = iterators;
043                        this.currentIndex = i;
044                }
045        }
046
047        @Override
048        public boolean hasNext() {
049                if(iterators != null && currentIndex < iterators.length)
050                        return true;
051                return false;
052        }
053
054        @Override
055        public T next() {
056                if(iterators == null || currentIndex >= iterators.length)
057                        throw new NoSuchElementException();
058                Iterator<? extends T> curr = iterators[currentIndex];
059                T nxt = curr.next();
060                if(!curr.hasNext())
061                        while(++currentIndex < iterators.length && !iterators[currentIndex].hasNext());
062                return nxt;
063        }
064
065        @Override
066        public void remove() {
067                throw new UnsupportedOperationException();
068        }
069
070}