[英]Managing Abstract subclass within a generic List in Java
泛型和摘要很難處理,因此在我盡力以簡單的方式解釋問題時請多多包涵。
我有以下課程:
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”為嗨,美國人可能會說“ Hello”為嗨。
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循環中指定人員類型的任何建議?
好。 這是一個如何完成的小例子:
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"));
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.