【发布时间】:2023-03-10 18:40:01
【问题描述】:
泛型和摘要很难处理,所以请耐心等待,我会尽力以简单的方式解释问题。
我有以下课程:
public class Community<T extends Person> {
List<T> people;
public void add(T person) {
people.add(person);
}
public List<T> getPeople() {
return people;
}
}
public abstract class Person {}
public class Aussie extends Person {}
下面是实例化澳大利亚社区的代码:
Aussie aus1 = new Aussie();
Aussie aus2 = new Aussie();
Community<Aussie> aussieCommunity = new Community<>();
aussieCommunity.add(aus1);
aussieCommunity.add(aus2);
现在让我们更进一步,说我有多个社区,我希望系统地存储在一个列表中,如下所示:
List<Community<?>> communities;
我希望你还在我身边,因为这是我的问题:
我需要编写一个代码来获取社区列表并显示每个人的详细信息 - 假设每个人的详细信息将在他们自己的班级中以不同方式访问。示例:澳大利亚人可能会说“Oi”作为 hi,美国人可能会说“Hello”作为 hi。
for (Community<?> community : communities) {
// I don't know what the type of community this is so, I use wildcard:
List<? extends Person> people = community.getPeople();
for (Type person : people) { // How do I specify the type of person eg Aussie/American etc here?
// Do something
}
}
关于如何在第二个 for 循环中指定人员类型的任何建议?
【问题讨论】:
-
为什么不在 Person 中使用抽象方法?
-
同意Mailkov。在 Person 中放置一个抽象方法并在所有子类中覆盖它。那么你就不需要知道它是什么样的人在循环中。继承会为你解决问题。
-
people.add(person);inCommunity#getPeople会给你一个错误。 -
遍历 Person 类并检查它是 instanceOf Aussie 还是 American 并在 if 循环中指定您的条件。
-
@JonnyHenly 那在
Community#add中,它不会给出编译错误。如果有代码试图在Community<?>上调用Community#add但 OP 没有发布任何这样做的代码,它只会出错。
标签: java class generics abstract