title: Understanding strange Java hash function
body: <p>Following is the source code for a hash function in <code>java.util.HashMap</code>. The comments explain well enough what it's accomplishing. <strong>but how?</strong> What are the <code>^</code> and <code>&gt;&gt;&gt;</code> operators doing? <strong>Can someone explain how the code actually <em>does</em> what the comments <em>say</em>?</strong></p>
  
  <pre><code>/**
   * Applies a supplemental hash function to a given hashCode, which
   * defends against poor quality hash functions.  This is critical
   * because HashMap uses power-of-two length hash tables, that
   * otherwise encounter collisions for hashCodes that do not differ
   * in lower bits. Note: Null keys always map to hash 0, thus index 0.
   */
  static int hash(int h) {
      // This function ensures that hashCodes that differ only by
      // constant multiples at each bit position have a bounded
      // number of collisions (approximately 8 at default load factor).
  
      h ^= (h &gt;&gt;&gt; 20) ^ (h &gt;&gt;&gt; 12);
      return h ^ (h &gt;&gt;&gt; 7) ^ (h &gt;&gt;&gt; 4);
  }
  </code></pre>