I saw it on a blog post that the following was a smart way to do a “reverse lookup” using getCode(int) in a Java enumeration:
public enum Status { WAITING(0), READY(1), SKIPPED(-1), COMPLETED(5); private static final Map<Integer,Status> lookup = new HashMap<Integer,Status>(); 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); } }
For me, a static map and a static initializer look like a bad idea, and my first thought was to encode the search like this:
public enum Status { WAITING(0), READY(1), SKIPPED(-1), COMPLETED(5); private int code; private Status(int code) { this.code = code; } public int getCode() { return code; } public static Status get(int code) { for(Status s : values()) { if(s.code == code) return s; } return null; } }
Are there any obvious problems with any method, and is there a recommended way to implement this kind of search?
java enums static-initializer
Armand Mar 15 '11 at 18:30 2011-03-15 18:30
source share