小编key*_*her的帖子

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

我有一些实现可迭代的基类

public class EntityCollection implements Iterable<Entity> {

    protected List<Entity> entities;

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

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

    ... etc
Run Code Online (Sandbox Code Playgroud)

这是子类.

public class HeroCollection extends EntityCollection {

    public void doSomeThing() { ... }
Run Code Online (Sandbox Code Playgroud)

我想做以下事情:

HeroCollection theParty = new HeroCollection();
theParty.add(heroA);
theParty.add(heroB);
for (Hero hero : theParty){
    hero.heroSpecificMethod();
}
Run Code Online (Sandbox Code Playgroud)

但是这在编译时失败了,因为迭代器是返回实体而不是英雄.我正在寻找一些限制列表的方法,使它只能包含子类的类型,这样我就可以在迭代器的结果上调用特定于子类的方法.我知道它必须以某种方式使用泛型,但我似乎无法弄清楚如何构造它.

java iterator

4
推荐指数
1
解决办法
64
查看次数

标签 统计

iterator ×1

java ×1