Re: iterator over superclass of collection
Chris Smith <cdsmith@twu.net> writes:
Frank Fredstone <none@not.no> wrote:
I mean just use the iterator straight from the vector:
public Iterator<? extends Aye> iterator() {
return ayes.iterator();
}
But then that wouldn't match Iterable<Aye>.
The important point here is that you REALLY want a value of the more
general type Iterable<? extends Aye>, and not an Iterable<Aye>. That
more general type correctly expresses the idea you want: namely, an
Iterable that returns elements which are assignment-compatible with Aye.
But that isn't what I want. Here is the scenario again. I have a class
that is a collection of instances of an interface, it is an iterable
collection of Ayes.
In the collection class I want to have a private implementation of
that interface. Below, my class can't extend a wildcard capture, and I
really don't want it to, because people aren't supposed to be able to
create instances of the interface, nor are they supposed to set
anything in the collection.
Below is the code I have. My question is still if there is something,
probably involving wildcards that would make it so that I don't have
to create an anonymous iterator class in my iterator method below. My
motivation is to clear up what looks like it could be a gap in my
understanding of generics.
import java.util.Iterator;
import java.util.Vector;
public class X implements Iterable<Aye> {
private class PrivateAye extends A implements Aye {
private int code = 0;
public PrivateAye(String eh, int n) {
super(eh);
setCode(n);
}
public int getCode() { return code; }
public void setCode(int n) { code = n; }
public String aye() { return a(); }
}
private Vector<PrivateAye> ayes;
public static void main(String[] args) throws Exception {
X x = new X();
x.go();
}
public void go() throws Exception {
ayes = new Vector<PrivateAye>();
ayes.add(new PrivateAye("a", 0));
ayes.add(new PrivateAye("b", 1));
for (Aye a : this) {
System.out.println(a.aye());
}
}
public Iterator<Aye> iterator() {
return new Iterator<Aye>() {
private Vector<? extends Aye> vec = ayes;
private Iterator<? extends Aye> it = vec.iterator();
public boolean hasNext() { return it.hasNext(); }
public Aye next() { return it.next(); }
public void remove() { it.remove(); }
};
}
}