我想要一个实现 T 类型的 Iterable(我们称之为 ImplIterable)的泛型类,它在某个类(不是泛型类类型)上实现 Iterable 接口;例如:
public class ImplIterable <T> implements Iterable<A> {
private A[] tab;
public Iterator<A> iterator() {
return new ImplIterator();
}
// doesn't work - but compiles correctly.
private class ImplIterator implements Iterator<A> {
public boolean hasNext() { return true; }
public A next() { return null; }
public void remove() {}
}
}
其中 A 是某个类。现在,此代码将无法编译:
ImplIterable iable = new ImplIterable();
for (A a : iable) {
a.aStuff();
}
但这将:
Iterable<A> = new ImplIterable();
for (A a : iable) {
a.aStuff();
}
我不明白为什么后者不能编译,如果 ImplIterable 正确实现了可迭代,为什么我不能迭代它。我做错了什么/是否有针对此类问题的解决方法?