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