如何限制迭代器仅返回子类的实例?

4

我有一些基类实现了iterable接口

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() { ... }

I would like to do the following:

HeroCollection theParty = new HeroCollection();
theParty.add(heroA);
theParty.add(heroB);
for (Hero hero : theParty){
    hero.heroSpecificMethod();
}

但是这无法在编译时成功,因为迭代器返回的是实体,而不是英雄。我正在寻找一种限制列表的方法,使其仅包含子类的类型,以便我可以在迭代器的结果上调用特定于子类的方法。我知道它必须使用泛型,但似乎无法确切地构造它。


英译中:Hero 应该继承 Entity。然后,创建一个 Hero 的 ArrayList。除非有关于 Hero 集合的特殊属性是你没告诉我们的。 - Robert Harvey
如示例所述,HeroCollection将提供除EntityCollection中方法之外的其他方法。下面建议可能这样做是个坏主意,但我不确定原因。 - Tom
1个回答

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<Hero>

(还要注意:您设计集合的方式(使用特定类型集合的单独方法)暗示您的代码可能设计不良。但是,如果确实如此,那是一个单独的问题。)


谢谢,我认为这正是我在寻找的。您能指点一下我,为什么我的子类集合具有特定方法可能不是一个好主意吗? - Tom
@keypusher 您具体想添加哪些方法? - user253751

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接