gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:06:43 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com