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.

1
  • 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. Commented Oct 1, 2012 at 8:06

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thx. I was missing the Colors.RED concept for declaring a constant: i.e. private static final Colors R = Colors.RED;
why we have added Color.class in map argument ??
9

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

2 Comments

public void setQuestionComponentsMap(Integer key, Object questionComponents){ what can i pass in the place of "Integer key"?coz now i am retrving enum keys.
If you can change the signature of that method then just replace the Integer argument with your Enum type...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.