2015-06-27 10 views
4

我有一個實現迭代我怎樣才能限制的迭代器返回一個子類的實例只?

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(); 
} 

但這種失敗在編譯的時候,因爲迭代器返回的實體,而不是英雄。我要尋找一些方法來限制列表,使得它只能包含類型的子類,這樣我可以調用的是特定於迭代的結果的子方法。我知道它必須以某種方式使用泛型,但我似乎無法弄清楚如何構造它。

+0

英雄應該擴大實體。然後,製作一個英雄陣列。除非你有沒有告訴我們關於英雄藏品的某些特殊屬性。 –

+0

@RobertHarvey如實例所指出的,一個HeroCollection將提供超出在EntityCollection附加方法。在下面提出這可能是一個壞主意,但我不知道爲什麼。 – keypusher

回答

6

我會建議作出EntityCollection通用。

public class EntityCollection<T extends Entity> implements Iterable<T> { 

    protected List<T> entities; 

    public EntityCollection() { 
     entities = new ArrayList<T>(); 
    } 

    public Iterator<T> iterator() { 
     return entities.iterator(); 
    } 

    ... etc 

public class HeroCollection extends EntityCollection<Hero> { 
    ... 
} 

然後,HeroCollection的iterator方法會返回一個Iterator <英雄>

(另請注意:您在設計集合(與特定類型的集合)不同的方法方式表明你代碼可以被設計得不好。但是,如果是這樣,這是一個獨立的問題。)

+0

謝謝,我認爲這正是我所尋找的。你可以點我在正確的方向儘可能爲什麼它可能是一個壞主意,我的子類的集合有具體的方法呢? – keypusher

+0

@keypusher你想添加什麼方法,具體是什麼? – immibis

相關問題