Iterator of Iterators

Given a Iterator which contain several iterator inside. The task is to iterate all elements inside these iterators. According to the following code, try to build up the entire class.

public class Iterators<T> implements Iterator<T>{
    public Iterators(Iterable<Iterator<T>> iterators){
        ...
    }
    ...
}

Think

  • It's a class implements iterator interface but also contains several iterators.
  • Image these iterator is a bucket, the unit is a iterator and the cursor of bucket index is a iterator element.
  • Set a current index to point at a iterator.

Solution

public class Iterators<T> implements Iterator<T>{
    Iterators<T> current;
    Iterators<Iterators<T>> cursor;
    public Iterators(Iterable<Iterator<T>> iterators){
        if(iterators == null)
            throw new IllegalArgumentException("Illegal Argument!");
        this.cursor = iterators;
    }

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

    @Override
    public boolean hasNext(){
        if(!current.hasNext())
            current = findNext();
        return current != null && current.hasNext();
    }

    private Iterator findNext(){
        while(cursor.hasNext()){
            current = cursor.next();
            if(current != null && current.hasNext())
                break;
        }
        return current;
    }

    @Override
    public void remove(){
        if(current!=null)
            current.remove();
    }
}

results matching ""

    No results matching ""