我有一個實現迭代我怎樣才能限制的迭代器返回一個子類的實例只?
public class EntityCollection implements Iterable<Entity> {
protected List<Entity> entities;
public EntityCollection() {
entities = new ArrayList<Entity>();
}
public Iterator<Entity> iterator() {
return entities.iterator();
}
... etc
這是一些子類的基類。
public class HeroCollection extends EntityCollection {
public void doSomeThing() { ... }
我想做到以下幾點:
HeroCollection theParty = new HeroCollection();
theParty.add(heroA);
theParty.add(heroB);
for (Hero hero : theParty){
hero.heroSpecificMethod();
}
但這種失敗在編譯的時候,因爲迭代器返回的實體,而不是英雄。我要尋找一些方法來限制列表,使得它只能包含類型的子類,這樣我可以調用的是特定於迭代的結果的子方法。我知道它必須以某種方式使用泛型,但我似乎無法弄清楚如何構造它。
英雄應該擴大實體。然後,製作一個英雄陣列。除非你有沒有告訴我們關於英雄藏品的某些特殊屬性。 –
@RobertHarvey如實例所指出的,一個HeroCollection將提供超出在EntityCollection附加方法。在下面提出這可能是一個壞主意,但我不知道爲什麼。 – keypusher