[英]Java: polymorphism applied to Map generic types
我希望有一個函數(例如)在兩種情況下都輸出Map的所有值:
Map<String, String> map1 = new HashMap<String, String>();
Map<String, Integer> map2 = new HashMap<String, Integer>();
output(map1, "1234");
output(map2, "4321");
以下似乎不起作用:
public void output(Map<String, Object> map, String key) {
System.out.println(map.get(key).toString());
}
不是Object
類型的String
和Integer
嗎?
Map<String, String>
不擴展Map<String, Object>
,就像List<String>
不擴展List<Object>
。 您可以將值類型設置為?
通配符:
public void output(Map<String, ?> map, String key) { // map where the value is of any type
// we can call toString because value is definitely an Object
System.out.println(map.get(key).toString());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.