Re: iterator over superclass of collection
Frank Fredstone wrote:
Is there something, probably involving wildcards that would make it so
that I don't have to create an anonymous iterator class in my iterator
method of the iterable (where the iterable is of instances of
interfaces which are implemented by private classes).
Sure. As long as Java Generics is implemented by erasure, probably
simplest approach is to use raw-type cast:
public Iterator<Aye> iterator() {
return (Iterator)ayes.iterator();
}
And then either ignore compiler's warning, or suppress it using
appropriate annotation.
What's wrong though with that simple, and type-safe anonymous wrapper of
iterator there?
If you use it often, there is no problem in generalizing it with extra
helper class like that:
public class IteratorWrapper<E> implements Iterator<E> {
protected Iterator<? extends E> iterator;
public IteratorWrapper(Iterator<? extends E> iterator) {
this.iterator = iterator;
}
public boolean hasNext() { return iterator.hasNext(); }
public E next() { return iterator.next(); }
public void remove() { iterator.remove(); }
}
Then, every time you'll need to reduce declared type of iterator
elements, you'll simply do that with:
public Iterator<Aye> iterator() {
return new IteratorWrapper<Aye>(ayes.iterator());
}
piotr