Dimitri Dimitri - 1 month ago 13
Java Question

Iterator of Iterator

I am trying to create an iterator of iterator, supporting any type in Java. The purpose is to iterate over the objects of the iterators.

But I have a type mismatch and I don't see how to initialize my implementation.

The first idea that I had in mind is to make my class implement

Iterator<Iterator<T>>
but this would not work because the next method will have the signature
public Iterator<T> next()
which does not correspond to what I want to do. Instead of returning of
Iterator<T>
, I want to return the type
T
.

So I create another interface which is very similar to the Iterator interface :

public interface MyIterator<T extends Iterator<T>> {

public boolean hasNext();

public T next();
}


My iterator takes a type T which is an iterator. Here is my implementation (without remove) :

public class IteratorOfIterator<T extends Iterator<T>> implements MyIterator<T> {

private T[] iterators;

private T currentIterator;

private int currentIndex;

public IteratorOfIterator(T[] iterators){
this.iterators = iterators;
this.currentIndex = 0;
this.currentIterator = iterators[currentIndex];
}

public boolean hasNext() {
return currentIndex < iterators.length - 1 || currentIterator.hasNext();
}

public T next() {
if(!this.currentIterator.hasNext()){
currentIndex++;
this.currentIterator = iterators[currentIndex];
}
return currentIterator.next();
}


If I want to test my iterator but I have a type mismatch, how can I initialize it? Here is an example of I want to do:

String[] strings = {"peanut","butter","coco","foo","bar"};

Object[] iterators = {strings};

MyIterator<String> myIterator = new IteratorOfIterator<String>(iterators); // <-- in this line


The error says :
Bound mismatch: The type String is not a valid substitute for the bounded parameter <T extends Iterator<T>> of the type IteratorOfIterator<T> IteratorOfIterator.java


How can I solve this problem? Thanks a lot for your advice.

PS: I totally understand the problem. I understand that, for instance, the type String does not implement MyIterator interface so this is why it's not a good substitute. My problem is I don't how can

Answer

This won't work,

public interface MyIterator<T extends Iterator<T>>

This means T must be an Iterator itself.

You don't want T do be restricted to a specific type,

public interface MyIterator<T>

BUT you want your Iterators to be of type Iterator<T>

public class IteratorOfIterator<T> implements Iterator<T> {

private Iterator<T>[] iterators;

private Iterator<T> currentIterator;

private int currentIndex;

public IteratorOfIterator(Iterator<T>[] iterators){
    this.iterators = iterators;
    this.currentIndex = 0;
    this.currentIterator = iterators[currentIndex];
}

so you can use Iterator instead of MyIterator again.