[英]Implementing the Java Iterator and Iterable Interface over an Object[] array
[英]Implementing Iterable by returning an Iterator over a sub-type
在以下代码中:
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
的定义BarIterable
为
public class BarIterable implements Iterable<? extends Bar> { ... // Error: A supertype may not specify any wildcard
解决这个问题的好方法是什么, 而不涉及实现Iterable<Foo>
(Iterable-implementation来自另一个不了解Foo的接口)?
我是否必须自己编写一个“解包”每个值的包装器迭代器类?
由于Foo
是Bar
的子类型,因此您可以直接转换List
。
return ((List<Bar>)(List<? extends Bar>) foos).iterator();
并压制警告。
由马库斯编辑:
或者,您可以使用middle-cast-trick直接强制转换迭代器:
return (Iterator<Bar>)(Iterator<? extends Bar>) foos.iterator();
结束编辑
使用Java 8,您可以流式传输元素并构造一个新的Bar
类型List
。
@Override
public Iterator<Bar> iterator() {
return foos.stream().<Bar>map((foo) -> foo /* considered a Bar */).collect(Collectors.toList()).iterator();
}
但是你要做的很多中间操作只是为了从超类型的角度来看List
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.