26

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.

tashuhka
  • 5,028
  • 4
  • 45
  • 64
user1568579
  • 295
  • 1
  • 4
  • 5
  • 6
    What have you tried? What happens when you use `EnumMap`? To get help you need to be more specific and show you've done your homework. – Sean Owen Oct 01 '12 at 08:06

2 Answers2

53

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

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
9

Just replace new HashMap<Integer, Object>() with new EnumMap<MyEnum, Object>(MyEnum.class).

Puce
  • 37,247
  • 13
  • 80
  • 152
  • public void setQuestionComponentsMap(Integer key, Object questionComponents){ what can i pass in the place of "Integer key"?coz now i am retrving enum keys. – user1568579 Oct 01 '12 at 10:13
  • If you can change the signature of that method then just replace the Integer argument with your Enum type... – Puce Oct 01 '12 at 10:48