![](/img/trans.png)
[英]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.