Inserting values ​​in Map <K, V>

I am programming my first application, and I am trying to create a map that will store some information.

I use ECLIPSE and I keep getting the same error, but I have Googled (actually DuckDuckGo-ed) and search on StackOverflow and I can’t find the error ... So I desperately came here.

Libraries are imported correctly (because ADT does this), and I assume that the Oracle documentation is fine, so ... why doesn't this work?

I mean, none of both methods work to insert a Key-Value pair into a map.

enter image description here

The interesting part is when viewing errors.

The first says Syntax error on token ",", { expected after this token
The second says Syntax error, insert "}" to complete ClassBody

I start a little desperate, I could not make the code easier! Thank you very much!

+7
source share
4 answers

There are two problems here. You must first put this into a method, and secondly, you cannot use the syntax [] ; You must use Map.put .

  public class Data { public static void main(String[] args) { Map<String, String> data = new HashMap<String, String>(); data.put("John", "Taxi Driver"); data.put("Mark", "Professional Killer"); } } 
+37
source

The two errors you have in your code are very different.

The first problem is that you initialize and populate your Map in the class body without an instruction. You can either have a static Map operator and static {//TODO manipulate Map} in the body of the class, or initialize and populate the map in the method or in the class constructor.

The second problem is that you cannot consider a Map syntactically as an array , therefore the operator data["John"] = "Taxi Driver"; should be replaced with data.put("John", "Taxi Driver") . If you already have the "John" key in your HashMap , its value will be replaced with "Taxi Driver".

+3
source

Syntax

 data.put("John","Taxi driver"); 
+2
source

Try this code

 HashMap<String, String> map = new HashMap<String, String>(); map.put("EmpID", EmpID); map.put("UnChecked", "1"); 
+2
source

All Articles