簡體   English   中英

Java:多態性應用於Map泛型類型

[英]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類型的StringInteger嗎?

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());
}

你正在尋找的是在Java中嘗試在Collections上引入多態,並稱之為Generics 更具體的用例, 通配符符合要求。

@manouti在他的回答中使用了無界通配符 (請參閱通配符鏈接中的詳細信息),但您可以使用更具體的內容: 上限有界通配符

例如Map<String, ? extends Object> Map<String, ? extends Object>其中Object通常是最具體但仍然是通用的類,必須從中派生所有使用的類。 例如,如果所有地圖中的值都有一個共同的父(或“超級”)類YourParentClass ,那么您可以在我的示例中用該類名替換Object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM