简体   繁体   English

Java:多态性应用于Map泛型类型

[英]Java: polymorphism applied to Map generic types

I want to have a function which (for example) outputs all the values of a Map in both cases: 我希望有一个函数(例如)在两种情况下都输出Map的所有值:

Map<String, String> map1 = new HashMap<String, String>();
Map<String, Integer> map2 = new HashMap<String, Integer>();
output(map1, "1234");
output(map2, "4321");

And the following doesn't seem to work: 以下似乎不起作用:

public void output(Map<String, Object> map, String key) {
    System.out.println(map.get(key).toString()); 
}

Are not both String and Integer of type Object ? 不是Object类型的StringInteger吗?

Map<String, String> does not extends Map<String, Object> , just like List<String> does not extend List<Object> . Map<String, String>不扩展Map<String, Object> ,就像List<String>不扩展List<Object> You can set the value type to the ? 您可以将值类型设置为? wildcard: 通配符:

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

The thing you are looking for is the attempt in Java to introduce polymorphism on Collections and is called Generics . 你正在寻找的是在Java中尝试在Collections上引入多态,并称之为Generics More specific to your use case, Wildcards will fit the bill. 更具体的用例, 通配符符合要求。

An Unbounded Wildcard (see details in Wildcards link) is used by @manouti in his answer, but you can use something more specific than just that: an Upper Bounded Wildcard . @manouti在他的回答中使用了无界通配符 (请参阅通配符链接中的详细信息),但您可以使用更具体的内容: 上限有界通配符

Eg Map<String, ? extends Object> 例如Map<String, ? extends Object> Map<String, ? extends Object> where Object usually is the most specific but still common class from which all used classes must be derived. Map<String, ? extends Object>其中Object通常是最具体但仍然是通用的类,必须从中派生所有使用的类。 For example, if the values in all of your Maps will have a common parent (or 'super') class YourParentClass , then you can replace Object in my example by that class name. 例如,如果所有地图中的值都有一个共同的父(或“超级”)类YourParentClass ,那么您可以在我的示例中用该类名替换Object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM