Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting into a Map<String, ?>

Tags:

java

generics

map

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?

like image 762
dev4life Avatar asked Jan 11 '12 20:01

dev4life


People also ask

How do you add a string to a map?

To insert the data in the map insert() function in the map is used. It is used to insert elements with a particular key in the map container. Parameters: It accepts a pair that consists of a key and element which is to be inserted into the map container but it only inserts the unique key.

Can we use string in map?

A map is an associative container that maps keys to values, provides logarithmic complexity for inserting and finding, and constant time for erasing single elements. It is common for developers to use a map to keep track of objects by using a string key.

How do I add a value to a map list?

1. Add values to a Map. The standard solution to add values to a map is using the put() method, which associates the specified value with the specified key in the map. Note that if the map already contains a mapping corresponding to the specified key, the old value will be replaced by the specified value.

How do you convert a map key and value in a string?

Convert a Map to a String Using Java Streams To perform conversion using streams, we first need to create a stream out of the available Map keys. Second, we're mapping each key to a human-readable String.


1 Answers

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.

like image 63
Adam Zalcman Avatar answered Sep 28 '22 17:09

Adam Zalcman