EnumMap的简单使用

想起前几天有个需求:文件上传如果出错,返回给用户的消息形如为: 错误的行号和原因:

2,4,6  商品id为必填

1,7   应用标识错误

8   时间格式错误

         由于错误原因是有限的,可以用枚举ErrMsgEnum表示。起初利用 HashMap<ErrMsgEnum,String> 来保存,了解了EnumMap内部是利用数组存储后,更改为EnumMap<ErrMsgEnum,String> 效率更高。


实现

  1.  ErrMsgEnum.java  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public enum ErrMsgEnum {  
  2.     required_item_id("商品id为必填项"),   
  3.     invalid_app_id("应用标识错误"),   
  4.     invalid_date("时间格式错误");  
  5.   
  6.     private String value;  
  7.   
  8.     private ErrMsgEnum(String value) {  
  9.     this.setValue(value);  
  10.     }  
  11.   
  12.     public String getValue() {  
  13.     return value;  
  14.     }  
  15.   
  16.     public void setValue(String value) {  
  17.     this.value = value;  
  18.     }  
  19.   
  20. }  

2. TestEnumMap.java 

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.util.EnumMap;  
  2. import java.util.Map;  
  3.   
  4. public class TestEnumMap {  
  5.       
  6.     public static void main(String[] args) {  
  7.     EnumMap<ErrMsgEnum,String> errMsgMap = new EnumMap<ErrMsgEnum,String>(ErrMsgEnum.class);  
  8.       
  9.     errMsgMap.put(ErrMsgEnum.required_item_id, "2,4,6");  
  10.     errMsgMap.put(ErrMsgEnum.invalid_app_id, "1,7");  
  11.     errMsgMap.put(ErrMsgEnum.invalid_date, "8");  
  12.    
  13.     for(Map.Entry<ErrMsgEnum,String> entry:errMsgMap.entrySet() ){  
  14.         System.out.println(entry.getValue()+ " " + entry.getKey().getValue());  
  15.     }     
  16.     }  
  17. }  

注意事项:

 

  1. 使用EnumMap时,必须指定枚举类型。All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created.

 

  2. key不能为null。 Null keys are not permitted.

  3.  EnumMap内部以数组实现,性能更好。Enum maps are represented internally as arrays.  This representation is extremely compact and efficient.

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值