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;
}
}
Solution: The idea is to store the entry set in a list and sort the list on the basis of values. Then fetch values and keys from the list and put them in a new hashmap. Thus, a new hashmap is sorted according to values.
If you want to make a mutable object as a key in the hashmap, then you have to make sure that the state change for the key object does not change the hashcode of the object. This can be done by overriding the hashCode() method. But, you must make sure you are honoring the contract with equals() also.
get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter.
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>
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With