Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the reason behind Enum.hashCode()?
    text
    copied!<p>The method hashCode() in class Enum is final and defined as super.hashCode(), which means it returns a number based on the address of the instance, which is a random number from programmers POV.</p> <p>Defining it e.g. as <code>ordinal() ^ getClass().getName().hashCode()</code> would be deterministic across different JVMs. It would even work a bit better, since the least significant bits would "change as much as possible", e.g., for an enum containing up to 16 elements and a HashMap of size 16, there'd be for sure no collisions (sure, using an EnumMap is better, but sometimes not possible, e.g. there's no ConcurrentEnumMap). With the current definition you have no such guarantee, have you?</p> <h3>Summary of the answers</h3> <p>Using <code>Object.hashCode()</code> compares to a nicer hashCode like the one above as follows:</p> <ul> <li>PROS <ul> <li>simplicity</li> </ul></li> <li>CONTRAS <ul> <li>speed</li> <li>more collisions (for any size of a HashMap)</li> <li>non-determinism, which propagates to other objects making them unusable for <ul> <li>deterministic simulations</li> <li>ETag computation</li> <li>hunting down bugs depending e.g. on a <code>HashSet</code> iteration order</li> </ul></li> </ul></li> </ul> <p>I'd personally prefer the nicer hashCode, but IMHO no reason weights much, maybe except for the speed.</p> <h2>UPDATE</h2> <p>I was curious about the speed and wrote a <a href="https://dl.dropboxusercontent.com/u/4971686/published/maaartin/so/EnumHashCodeBenchmark.java" rel="nofollow noreferrer">benchmark</a> with surprising <a href="https://microbenchmarks.appspot.com/runs/6af10de0-e379-4aad-a354-cbc8815a466c" rel="nofollow noreferrer">results</a>. For a price of a single field per class you can a deterministic hash code which is nearly <em>four times faster</em>. Storing the hash code in each field would be even faster, although negligibly.</p> <p><img src="https://i.stack.imgur.com/rtb85.png" alt=""></p> <p>The explanation why the standard hash code is not much faster is that it can't be the object's address as objects gets moved by the GC.</p> <h2>UPDATE 2</h2> <p>There are some strange things <a href="https://stackoverflow.com/q/24222991">going on</a> with the <code>hashCode</code> performance in general. When I understand them, there's still the open question, why <code>System.identityHashCode</code> (reading from the object header) is way slower than accessing a normal object field.</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