使用枚举作为地图的关键
我想使用enum
作为键和对象作为值。 以下是示例代码段:
public class DistributorAuditSection implements Comparable{ 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(); } this.questionComponentsMap.put(key,questionComponents); } }
它现在是一个普通的hashmap,带有整数键,对象作为值。 现在我想将其更改为Enummap
。 这样我就可以使用enum
键了。 我也不知道如何使用Enummap
检索值。
它与Map
Just Declare enum
原理相同,并将其用作EnumMap
Key
。
public enum Color { RED, YELLOW, GREEN } Map enumMap = new EnumMap(Color.class); enumMap.put(Color.RED, "red"); String value = enumMap.get(Color.RED);
你可以在这里找到更多关于Enums
信息
只需用new EnumMap
替换new HashMap
new EnumMap
。