【发布时间】:2014-12-19 12:52:41
【问题描述】:
在以下代码中:
public class Bar { ... }
public class Foo extends Bar { ... }
public class BarIterable implements Iterable<Bar> {
List<Foo> foos = ...
@Override
public Iterator<Bar> iterator() {
return foos.iterator(); // Error: Type mismatch ...
}
}
由于foos.iterator() 返回的是Iterable<Foo> 而不是Iterable<Bar>,因此我在指定位置出现错误。不幸的是,简单的演员阵容是行不通的:
return (Iterator<Bar>) foos.iterator(); // Error: Cannot cast ...
Java 也不允许我将 BarIterable 的定义更改为
public class BarIterable implements Iterable<? extends Bar> { ... // Error: A supertype may not specify any wildcard
不涉及实现Iterable<Foo>(Iterable-implementation 来自另一个不了解 Foo 的接口)的解决此问题的好方法是什么?
我是否必须为自己编写一个“解包”每个值的包装迭代器类?
【问题讨论】:
-
我不确定,但看起来您正在实现继承,并且这一行
public class BarIterable implements Iterable<Bar>应该改为public class BarIterable extends Iterable<Bar>,除非我弄错了。 -
@AlvinBunk
Iterable是一个接口,所以我肯定需要使用implements,而不是extends。 -
你是怎么得到
foos的? -
好的,你能发布更多你的代码以便我在 Eclipse 中试用吗?
-
你不能把你的
foos改成List<Bar> foos吗?