【问题标题】:Using enum as key for map [closed]使用枚举作为地图的键[关闭]
【发布时间】:2012-10-01 08:04:01
【问题描述】:

我想使用enum 作为键和一个对象作为值。这是示例代码sn-p:

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

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

【问题讨论】:

  • 你试过什么?当您使用EnumMap 时会发生什么?要获得帮助,您需要更加具体并表明您已完成作业。

标签: java enums


【解决方案1】:

原理与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);

你可以找到更多关于Enumshere

【讨论】:

  • 谢谢。我错过了声明常量的 Colors.RED 概念:即 private static final Colors R = Colors.RED;
  • 为什么我们在地图参数中添加了 Color.class ??
【解决方案2】:

只需将new HashMap&lt;Integer, Object&gt;() 替换为new EnumMap&lt;MyEnum, Object&gt;(MyEnum.class)

【讨论】:

  • public void setQuestionComponentsMap(Integer key, Object questionComponents){ 我可以通过什么来代替“Integer key”?因为现在我正在检索枚举键。
  • 如果您可以更改该方法的签名,那么只需将 Integer 参数替换为您的 Enum 类型...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
  • 2012-03-02
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
相关资源
最近更新 更多