title: How hashcodes for enums are calculated in Java, and combining enum hashCodes for a HashMap's key
body: <p>I have a class that contains different enums (different types). This class is used as key for a <code>HashMap</code>. The classes hashCode currently is implemented like this:</p>
  
  <pre><code>  public static class Key implements Comparable&lt;Key&gt; {
      final int a;
      final Enum1 enum1;
      final Enum2 enum2;
  
      @Override
      public int hashCode() {
        return a ^ enum1.hashCode() ^ enum2.hashCode();
      }
  
      // ... definition of equals and toString ...
    }
  </code></pre>
  
  <p>Now if enums hashCode would just return the index of the enum value in the enum's definition, this would not be optimal (too many clashes). The method definition for <code>Enum.hashCode()</code> is this:</p>
  
  <pre><code>/**
   * Returns a hash code for this enum constant.
   *
   * @return a hash code for this enum constant.
   */
  public final int hashCode() {
      return super.hashCode();
  }
  </code></pre>
  
  <p>Assuming this delegates to <code>Object.hashCode()</code>, everything should be fine because for every enum constant there only exists one instance, and <code>Object.hashCode()</code> will in theory be something like an integer derived from the internal address of the object. Am I right?</p>
  
  <p>PS: Of course you will have to use something more complex when the same enum is used several times in a key.</p>