I have a class and it has a couple data structures in it among which is a hashmap. But I want the hashmap to have default values so I need to preload it. How do I do this since I can't use put method inside the object?
class Profile
{
HashMap closedAges = new HashMap();
closedAges.put("19");
}
I fixed it with this but I had to use a method within the object.
class Profile
{
HashMap closedAges = loadAges();
HashMap loadAges()
{
HashMap closedAges = new HashMap();
String[] ages = {"19", "46", "54", "56", "83"};
for (String age : ages)
{
closedAges.put(age, false);
}
return closedAges;
}
}
You could do this:
Map<String, String> map = new HashMap<String, String>() {{
put("1", "one");
put("2", "two");
put("3", "three");
}};
This java idiom is called double brace initialization.:
The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated.
You want to do this in the constructor of your class, for instance
class Example {
Map<Integer, String> data = new HashMap<>();
public Example() {
data.put(1, "Hello");
data.put(2, "World");
}
}
or to use the freakish double brace initialization feature of Java:
class Example {
Map<Integer, String> data;
public Example() {
/* here the generic type parameters cannot be omitted */
data = new HashMap<Integer, String>() {{
put(1, "Hello");
put(2, "World");
}};
}
}
And finally, if your HashMap
is a static field of your class, you can perform the initialization inside a static
block:
static {
data.put(1, "Hello");
...
}
In order to address Behes comment, if you are not using Java 7, fill the <>
brackets with your type parameters, in this case <Integer, String>
.