I want to have a function which (for example) outputs all the values of a Map 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 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?
Map<String, String> does not extends Map<String, Object>, just like List<String> does not extend 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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With