Conveniently map between enum and int / String

前端 未结 18 1849
陌清茗
陌清茗 2020-11-28 01:07

When working with variables/parameters that can only take a finite number of values, I try to always use Java\'s enum, as in

public enum BonusT         


        
18条回答
  •  旧时难觅i
    2020-11-28 01:17

    I found this on the web, it was very helpful and simple to implement. This solution was NOT made by me

    http://www.ajaxonomy.com/2007/java/making-the-most-of-java-50-enum-tricks

    public enum Status {
     WAITING(0),
     READY(1),
     SKIPPED(-1),
     COMPLETED(5);
    
     private static final Map lookup 
          = new HashMap();
    
     static {
          for(Status s : EnumSet.allOf(Status.class))
               lookup.put(s.getCode(), s);
     }
    
     private int code;
    
     private Status(int code) {
          this.code = code;
     }
    
     public int getCode() { return code; }
    
     public static Status get(int code) { 
          return lookup.get(code); 
     }
    

    }

提交回复
热议问题