Putting into a Map<String, ?>

13,395

Solution 1

If you want to put values of type X into a generic Map you need to declare the Map as Map<String, ? super X>. In your example X is String, so:

public String doThis(Map<String, ? super String> context){
.....
}

Map<String, ? super X> means: a map with keys of type String and values of a type which is X or a super-type of X. All such maps are ready to accept String instances as keys and X instances as values.

Solution 2

Remember PECS (Producer Extends, Consumer Super). You have a consumer (putting in), therefore it cannot be extends.

Share:
13,395

Related videos on Youtube

dev4life
Author by

dev4life

I likey the jquery.

Updated on June 04, 2022

Comments

  • dev4life
    dev4life almost 2 years

    So I have a Map that has some values in it being passed into a method:

    public String doThis(Map<String, ?> context){
    .....
    }
    

    And I'm trying to insert an addition attribute to this Map

    String abc="123";
    context.put("newAttr",abc);
    

    But I am getting this error:

    The method put(String, capture#8-of ?) in the type Map is not applicable for the arguments (String, String)

    Is there anyway to perform this put without "cloning" the Map?

  • ruakh
    ruakh over 12 years
    +1, but your last paragraph has a typo: you mean super rather than extends. :-)