实现 Iterable 的通用类
我想要一个实现 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(如果它正确实现了 iterable)。我做错了什么/是否有解决此类问题的方法?
I want to have a generic class that implements Iterable (let's call it ImplIterable) of type T that implements an Iterable interface over some class (that isn't of the generic class type); for example:
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() {}
}
}
Where A is some class. Now, this code won't compile:
ImplIterable iable = new ImplIterable();
for (A a : iable) {
a.aStuff();
}
But this will:
Iterable<A> = new ImplIterable();
for (A a : iable) {
a.aStuff();
}
I don't understand why the latter doesn't compile and why can't I iterate over ImplIterable if it properly implements iterable. Am I doing something wrong/is there some workaround for this type of problems?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您使用不带泛型参数的泛型类时,该类中的所有泛型都会被禁用。
由于
ImplIterable
是泛型的,并且您将其用作非泛型类,因此它内部的泛型参数消失了,并且它变成了Iterable
(非泛型)对象
。When you use a generic class without a generic parameter, all generics in that class are disabled.
Since
ImplIterable
is generic, and you're using it as a non-generic class, the generic parameters inside of it vanish, and it becomes anIterable
(non-generic) ofObject
s.