Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enum as key for map [closed]

Tags:

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.

like image 723
user1568579 Avatar asked Oct 01 '12 08:10

user1568579


People also ask

Can we use enum as key in map?

In HashMap, there is no constraint. You can use Enum as well as any other Object as key.

Can we use enum as key in HashMap?

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.

Can you map an enum?

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.

What happens if key is not present in map?

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.


1 Answers

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

like image 176
Amit Deshpande Avatar answered Oct 19 '22 00:10

Amit Deshpande