Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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<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?

like image 551
tsotsi Avatar asked Jul 17 '26 07:07

tsotsi


1 Answers

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());
}
like image 97
M A Avatar answered Jul 18 '26 20:07

M A