使用枚举作为地图的关键

时间:2012-10-01 08:04:01

标签: java enums

我想将enum用作键,将对象用作值。以下是示例代码段:

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);  
     }
}

现在是一个普通的散列图,其中包含整数键和对象作为值。现在我想将其更改为Enummap。这样我就可以使用enum键。我也不知道如何使用Enummap检索值。

2 个答案:

答案 0 :(得分:43)

Map的原则相同,只需声明enum并将其用作KeyEnumMap

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);

您可以找到有关Enums here

的更多信息

答案 1 :(得分:5)

只需将new HashMap<Integer, Object>()替换为new EnumMap<MyEnum, Object>(MyEnum.class)