user826323
user826323

Reputation: 2338

java generic array with iterator

I have a code like the following.

public class DefaultIterator<E> implements Iterator<E> {
private E[] array;
private int i = 0;

public DefaultIterator(E[] array) {
    this.array = array;
}

@Override
public boolean hasNext() {
    return false;
}

@Override
public E next() {
    return array[i++];
}

@Override
public void remove() {

}

}

// here is my execution.
    public Iterator<String> createNewIterator(Iterator<String>... generalIterators)    {
    return new DefaultIterator<Iterator<String>[]>(generalIterators);
}

I am getting the compilation error at the execution code. can somebody explain why it is failing and how to fix it?

Thanks.

Upvotes: 0

Views: 235

Answers (2)

Tim Bender
Tim Bender

Reputation: 20442

So the complaint is that none of the generic types match up between the field declaration, the constructor declaration, and the method declaration.

You want:

public Iterator<String> createNewIterator(String... generalIterators)    {
    return new DefaultIterator<String>(generalIterators);
}

Upvotes: 3

My-Name-Is
My-Name-Is

Reputation: 4942

Your return type is another one than expected! DefaultIterator<Iterator<String>[]> isn't compatible with Iterator<String> Choose DefaultIterator<Iterator<String>[]> as your return type, this should solve it.

Upvotes: 0

Related Questions