How to add values for java generic map with undetermined “?” value type

  • A+

I've seen this kind of declaration in jdk 8 sample:

    Map<String, ?> map = new HashMap<>(3);//OK 

But when I tried to add value to "map", I didn't succeed:

    map.put("abc", Optional.of(5));     map.put("kk", "xyz"); 

Both fail to compile. I wish to know:

(1) What does "?" indicate in Map declaration above?

(2) How to give values to this "map"?


Question (1)

? is called wildcard generic type.It can be used with any type, but you need to specify type fist as Map is an abstract class. 

Question (2)

for you to give value to this map its either you use Upper bound or Lower bound.

The following are guidelines when using upper bound or lower bound

? extends Type   - is used for read access only ? super Type     - is used for write access only. 

PECS in short Produces(write acccess) -uses Extends while Consumes(read access) - uses Super

Map<String, ? super Object> map = new HashMap<>(3);//OK     map.put("abc",Optional.of(5));     map.put("kk","xyz"); map.forEach((k,v)->System.out.println(k+"/t"+v)); 


kk  xyz abc Optional[5]  Process finished with exit code 0 

Additional Notes

Unbounded wildcard ?

 List<?> l = new ArrayList<String>(); 

Wildcard with an upper bound ? extends type

 List<? extends Exception> l = new ArrayList<RuntimeException>(); 

Wildcard with a lower bound ? super type

 List<? super Exception> l = new ArrayList<Object>(); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: