I want to use enum
as keys and a object as value. Here is the sample code snippet:
public class DistributorAuditSection implements Comparable<DistributorAuditSection>{ private Map questionComponentsMap; public Map getQuestionComponentsMap(){ return questionComponentsMap; } public void setQuestionComponentsMap(Integer key, Object questionComponents){ if((questionComponentsMap == null) || (questionComponentsMap != null && questionComponentsMap.isEmpty())){ this.questionComponentsMap = new HashMap<Integer,Object>(); } this.questionComponentsMap.put(key,questionComponents); } }
It is now a normal hashmap with integer keys and and object as values. Now I want to change it to Enummap
. So that I can use the enum
keys. I also don't know how to retrieve the value using Enummap
.
In HashMap, there is no constraint. You can use Enum as well as any other Object as key.
In HashMap, we can use Enum as well as any other object as a key. It doesn't allow storing null key. It allows to store the null keys as well values, but there should be only one null key object and there can be any number of null values. HashMap internally uses the HashTable.
To use the map() method with enums: Use the Object. keys() method to get an array of the enum's keys. Use the map() method to iterate over the array.
If the key is not present in the map, get() returns null. The get() method returns the value almost instantly, even if the map contains 100 million key/value pairs.
It the same principle as Map
Just Declare enum
and use it as Key
to EnumMap
.
public enum Color { RED, YELLOW, GREEN } Map<Color, String> enumMap = new EnumMap<Color, String>(Color.class); enumMap.put(Color.RED, "red"); String value = enumMap.get(Color.RED);
You can find more about Enums
here
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