Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use a <code>static Map&lt;Integer,TestEnum&gt;</code> with a <code>static</code> initializer that populates it with the <code>TestEnum</code> values keyed by their <code>number</code> fields.</p> <p>Note that <code>findByKey</code> has been made <code>static</code>, and <code>number</code> has also been made <code>final</code>.</p> <pre><code>import java.util.*; public enum TestEnum { ONE(1), TWO(2), SIXTY_NINE(69); private final int number; TestEnum(int number) { this.number = number; } private static final Map&lt;Integer,TestEnum&gt; map; static { map = new HashMap&lt;Integer,TestEnum&gt;(); for (TestEnum v : TestEnum.values()) { map.put(v.number, v); } } public static TestEnum findByKey(int i) { return map.get(i); } public static void main(String[] args) { System.out.println(TestEnum.findByKey(69)); // prints "SIXTY_NINE" System.out.println( TestEnum.values() == TestEnum.values() ); // prints "false" } } </code></pre> <p>You can now expect <code>findByKey</code> to be a <code>O(1)</code> operation.</p> <h3>References</h3> <ul> <li><a href="http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.7" rel="noreferrer">JLS 8.7 Static initializers</a></li> <li><a href="http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9" rel="noreferrer">JLS 8.9 Enums</a></li> </ul> <h3>Related questions</h3> <ul> <li><a href="https://stackoverflow.com/questions/335311/static-initalizer-in-java">Static initalizer in Java</a></li> <li><a href="https://stackoverflow.com/questions/507602/how-to-initialise-a-static-map-in-java">How to Initialise a static Map in Java</a></li> </ul> <hr> <h3>Note on <code>values()</code></h3> <p>The second <code>println</code> statement in the <code>main</code> method is revealing: <code>values()</code> returns a newly allocated array with every invokation! The original <code>O(N)</code> solution could do a little better by only calling <code>values()</code> once and caching the array, but that solution would still be <code>O(N)</code> on average.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload