Java: polymorphism applies to generic map types
I want to have a function that (for example) outputs all Map values ββin both cases:
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 work:
public void output(Map<String, Object> map, String key) {
System.out.println(map.get(key).toString());
}
Aren't they String
also Integer
type Object
?
source to share
Map<String, String>
does not expand Map<String, Object>
, just as it List<String>
does not extend List<Object>
. You can set the value type to a 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());
}
source to share
What you are looking for is Java's attempt to implement polymorphism on Collections
and is called Generics . More specifically for your use case, Wildcards will match the count.
The unbounded wildcard (see Wildcards link for details) is used by @manouti in his answer, but you can use something more specific than just: Upper bounded wildcard .
eg. Map<String, ? extends Object>
where is Object
usually the most specific but still general class from which all used classes should be derived. For example, if the values ββin all your Maps will have a common parent (or super) class YourParentClass
, then you can replace Object
in my example with this class name.
source to share