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

标签 java iterator

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

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

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

最佳答案

我建议使 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

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

关于java - 如何限制迭代器只返回子类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31084598/

相关文章:

java - JAVA中检测回车符(\r\n)

java - 在 Java 中测试紧密耦合的类

iterator - 在 Julia 中如何巧妙地处理零维度和迭代器

python - 尽可能避免将迭代器转换为列表

rust - 使用 iter.map,为什么闭包有效但直接传递函数却无效?

php - 未知扩展名时检查文件是否存在

c++ - 使用迭代器打印列表

java - 递归如何与 Java 8 Stream 一起工作?

Java Hadoop FileSystem 对象到 File 对象

java - 创建用户提示并模拟交互