What is proper way to define Map<String, ?> method parameter

generics, java

Solution

`String map2String(Map<String, ?> map){...}` is correct (`? extends Object` is redundant)

The first one won't work because you wouldn't be able to call

Map<String,Integer> myMap = {...}
map2String(myMap); // Map<String,Integer>  is not  Map<String,Object>  

The proper type for the entry variable is `Entry<String, ?>` as you suspected.

Problem

I have a custom Map to String method. It is meant to be used with any kind of Map that has String keys, not restricted to some specific map value type. The map values might have come from `javax.jms.Message.getObjectProperty(String name)` method, for example, or just be plain Strings. Which of following is the most "proper" method signature to use, and why, or are all equal? ``` String map2String(Map<String, Object> map){...} ``` or ``` String map2String(Map<String, ?> map){...} ``` or ``` String map2String(Map<String, ? extends Object> map){...} ``` or (added edit) ``` <E> String map2String(Map<String, ? extends E> map){...} ``` or something else? Also, the method contains for-each loop somewhat like this: ``` for(Entry<String, ?> entry : map.entrySet()) { String key = entry.getKey(); String value = entry.getValue().toString(); } ``` Which is "proper" type for the `entry` variable, does it matter (except the incompatible combination of `?` in the map, `Object` in the entry type).

Original source