001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *  
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *  
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License. 
018 *  
019 */
020package org.apache.directory.shared.util;
021
022
023import java.util.Iterator;
024import java.util.NoSuchElementException;
025
026import org.apache.directory.shared.i18n.I18n;
027
028
029/**
030 * An Iterator that joins the results of many iterators.
031 * 
032 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
033 */
034public class JoinIterator implements Iterator<Object>
035{
036    /** the iterators whose results are joined */
037    private final Iterator<?>[] iterators;
038
039    private int index;
040
041
042    /**
043     * Creates an Iterator that joins other Iterators.
044     * 
045     * @param iterators
046     *            the Iterators whose results are joined
047     * @throws IllegalArgumentException
048     *             if a null array argument, or one with less than 2 elements is
049     *             used
050     */
051    public JoinIterator( Iterator<?>[] iterators )
052    {
053        if ( iterators == null || iterators.length < 2 )
054        {
055            throw new IllegalArgumentException( I18n.err( I18n.ERR_04397 ) );
056        }
057
058        this.iterators = new Iterator[ iterators.length ];
059        System.arraycopy( iterators, 0, this.iterators, 0, iterators.length );
060        this.index = 0;
061    }
062
063
064    public void remove()
065    {
066        throw new UnsupportedOperationException();
067    }
068
069
070    public boolean hasNext()
071    {
072        for ( /** nada */
073        ; index < iterators.length; index++ )
074        {
075            if ( iterators[index].hasNext() )
076            {
077                return true;
078            }
079        }
080
081        return false;
082    }
083
084
085    public Object next()
086    {
087        for ( /** nada */
088        ; index < iterators.length; index++ )
089        {
090            if ( iterators[index].hasNext() )
091            {
092                return iterators[index].next();
093            }
094        }
095
096        throw new NoSuchElementException();
097    }
098}