Reputation: 193
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");
Upvotes: 7
Views: 23471
Reputation: 199
Assuming that you are wishing to put a value to a HashMap at the same time you initialize it. I will suggest you this "magic" Java syntax:
Try this:
public class ClassName {
HashMap<String, String> hashMap = new HashMap<String, String>(){
{
put("one", "two");
put("two", "three");
}
};
/*
Other code and constructor can go here.
....
....
*/
}
Indeed, from Java anywhere even on a non-function code section, you can immediately call the object instance function and properties by following the pattern shown above;-)
Upvotes: 2
Reputation: 716
Try this:
public class Class {
HashMap arrayList1 = new HashMap<>();;
arrayList1.put("32", "Bangalore");
arrayList1.put("32", "India");
}
Upvotes: -1
Reputation: 480
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.
Upvotes: 23