Re: iterator over superclass of collection
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Frank Fredstone schreef:
Lew <lew@nospam.lewscanon.com> writes:
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).
You have received the same answer from several people. You might
consider accepting the advice.
The <? extends Aye> gives you the ability to directly use the
collection's iterator (Iterator<? extends Aye>) to manipulate
instances of Aye that happen to be PrivateAye, but no one using the
Iterator can know that. The behavior of each object accessed via the
Iterator will be PrivateAye's behavior, as my SSCCE upthread shows
you, but the access will only be through a variable of type Aye.
What of that fails to achieve what you want?
As far as I can tell, it's not possible, unless this is an answer to a
different question than the one I've been asking. Given a class that
is an iterable collection of instances of an interface:
class X implements Iterable<Aye> { ... }
the iterator can't return Iterator <? extends Aye>, and this is not
legal:
class X implements Iterable<? extends Aye> { ... }
Okay, things are getting clearer now. You gave the impression you
didn???t want to use the joker. I didn???t find a good solution either.
The easiest I can come up with is the following:
import java.util.*;
interface Aye {
String aye();
}
class A {
private String a;
public A(String eh) {
a = eh;
}
String a() {
return a;
}
}
public class C implements Iterable<Aye> {
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 ArrayList<PrivateAye> ayes;
public static void main(String[] args) throws Exception {
C x = new C();
x.go();
}
public void go() throws Exception {
ayes = new ArrayList<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() {
List<Aye> temp = new ArrayList<Aye>(ayes);
return temp.iterator();
// or even return new ArrayList<Aye>(ayes).iterator();
}
}
In this particular case, it is a but superfluous since Iterator does not
allow the addition of elements. But the extra step is necessary to
ensure type-safety.
H.
- --
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
iD8DBQFGJzfBe+7xMGD3itQRAqATAJ0XUtRKiDGzSdeIZfBC53LOQqpqowCdEDdy
HjRUvY9MlmdEfl6MnIFMEyY=
=GCWT
-----END PGP SIGNATURE-----