使用枚举作为地图的关键

use*_*579 18 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);  
     }
}
Run Code Online (Sandbox Code Playgroud)

它现在是一个普通的hashmap,带有整数键,对象作为值.现在我想把它改成Enummap.这样我就可以使用这些enum键.我也不知道如何使用检索值Enummap.

Ami*_*nde 46

它与MapJust Declare的原理相同,enum并将其Key用于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);
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到更多相关信息Enums


Puc*_*uce 6

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