title: Java enum reverse look-up best practice
body: <p>I saw it <a href="http://www.ajaxonomy.com/2007/java/making-the-most-of-java-50-enum-tricks">suggested on a blog</a> that the following was a reasonable way to do a "reverse-lookup" using the <code>getCode(int)</code> in a Java enum:</p>
  
  <pre><code>public enum Status {
      WAITING(0),
      READY(1),
      SKIPPED(-1),
      COMPLETED(5);
  
      private static final Map&lt;Integer,Status&gt; lookup 
              = new HashMap&lt;Integer,Status&gt;();
  
      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); 
      }
  }
  </code></pre>
  
  <p>To me, the static map and the static initializer both look like a bad idea, and my first thought would be to code the lookup as so:</p>
  
  <pre><code>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;
      }
  }
  </code></pre>
  
  <p>Are there any obvious problems with either method, and is there a recommended way to implement this kind of lookup?</p>