Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add keys and values to a Hashmap while getting 'cannot resolve put symbol' error

I am working with Android Studio 1.4.1. I had just created a Hashmap and was following a tutorial (in Java) on how to populate and manipulate it.

However, I get a 'cannot resolve symbol put' error and the "put" command is in red.

The image I added shows the auto complete snapshot and although java.util.HashMap is imported, there isn't any "put" command that is available in autocomplete. The available commands also are showing in red. I tried to use them instead of the "put" command. I keep having this type of problem all along. How can I fix it?

Image

import java.util.HashMap;

HashMap<String, String> pozisyon = new HashMap<String, String>();
pozisyon.put("SKale", "a8");
like image 875
Aziz S. Kural Avatar asked Dec 02 '22 13:12

Aziz S. Kural


1 Answers

You cannot add elements in HashMap fields outside of methods. Things like this won’t work:

public class Class {
    HashMap<String, String> hashMap = new HashMap<String, String>();
    hashMap.put("one", "two");
}

If you want to achieve that, put it in the constructors, like so:

public class Class {
    HashMap<String, String> hashMap = new HashMap<String, String>();

    public Class() {
        hashMap.put("one", "two");
    }
}

Another way you can do it is in a static block.

like image 198
Lubo Kanev Avatar answered Dec 10 '22 12:12

Lubo Kanev