How to add keys and values to a Hashmap while getting 'cannot resolve put symbol' error
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.
Aziz S. Kural
Updated on June 24, 2022Comments
-
Aziz S. Kural almost 2 years
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?
import java.util.HashMap; HashMap<String, String> pozisyon = new HashMap<String, String>(); pozisyon.put("SKale", "a8");