泛型和摘要令人难以置信,所以请耐心等待我尽力以简单的方式解释问题。
我有以下课程:
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;
我希望你和我在一起,因为这是我的问题:
我需要编写一个代码,该代码将获取社区列表并显示每个人的详细信息 - 假设每个人的详细信息将在他们自己的班级中以不同方式访问。例如:澳大利亚人可能会说&#34; Oi&#34;嗨,美国人可能会说&#34;你好&#34;嗨。
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循环中指定人员类型的任何建议?
答案 0 :(得分:0)
确定。以下是一个如何完成的小例子:
public abstract class Person {
public final String say(String sentance) {
StringTokenizer tokenizer = new StringTokenizer(sentance);
StringBuilder sb = new StringBuilder();
while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken();
String slang = getSlang(word);
sb.append(slang != null ? slang : word);
sb.append(tokenizer.hasMoreTokens() ? " " : "");
}
return sb.toString();
}
private String getSlang(String word) {
return getSlangMap().get(word);
}
protected abstract Map<String, String> getSlangMap();
}
public class Aussi extends Person {
@Override
protected Map<String, String> getSlangMap() {
Map<String, String> slangMap = new HashMap<>();
slangMap.put("hi", "Oi");
slangMap.put("there", "theeer");
return slangMap;
}
}
public class Swede extends Person {
@Override
protected Map<String, String> getSlangMap() {
Map<String, String> slangMap = new HashMap<>();
slangMap.put("hi", "hejsan");
slangMap.put("there", "där");
return slangMap;
}
}
public class CommunityTest {
@Test
public void testSayHiThere() throws Exception {
Aussi au1 = new Aussi();
Aussi au2 = new Aussi();
Community<Aussi> aussiCommunity = new Community<>();
aussiCommunity.add(au1);
aussiCommunity.add(au2);
Swede sw1 = new Swede();
Swede sw2 = new Swede();
Community<Swede> swedeCommunity = new Community<>();
swedeCommunity.add(sw1);
swedeCommunity.add(sw2);
List<Community<? extends Person>> communities = new ArrayList<>();
communities.add(aussiCommunity);
communities.add(swedeCommunity);
for (Community<? extends Person> community : communities) {
for (Person person : community.getPeople()) {
System.out.println(person.say("hi there"));
}
}
}
}