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

Java 如何限制迭代器只返回子类的实例?,java,iterator,Java,Iterator,我有一些实现iterable的基类 public class EntityCollection implements Iterable<Entity> { protected List<Entity> entities; public EntityCollection() { entities = new ArrayList<Entity>(); } public Iterator<Entity>

我有一些实现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
我想做以下工作:

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

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

我建议使用
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> {
    ...
}
公共类EntityCollection实现了Iterable{
受保护名单实体;
公共实体集合(){
实体=新的ArrayList();
}
公共迭代器迭代器(){
返回entities.iterator();
}
等
公共类集合扩展了EntityCollection{
...
}
然后,HeroCollection的迭代器方法将返回一个迭代器


(另请注意:您设计集合的方式(针对特定类型的集合使用单独的方法)表明您的代码可能设计得很糟糕。但是,如果是这样,这是一个单独的问题。)

Hero应该扩展实体。然后,创建一个英雄数组列表。除非您没有告诉我们英雄集合的某些特殊属性。@RobertHarvey如示例中所述,Hero集合将提供EntityCollection之外的其他方法。下面有人建议,这可能是个坏主意,但我不确定为什么。谢谢,我想这正是我想要的。你能给我指出一个正确的方向吗?为什么我的子类集合使用特定的方法可能不是一个好主意?@keypusher你想添加哪些方法,具体来说?
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> {
    ...
}