Using enum as key for map [closed]

2020-02-05 11:54发布

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.

标签: java enums
2条回答
The star\"
2楼-- · 2020-02-05 12:16

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

查看更多
你好瞎i
3楼-- · 2020-02-05 12:21

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

查看更多
登录 后发表回答