title: Are there different ways to calculate the table index in HashMap
body: <p><a href="http://en.wikipedia.org/wiki/Hash_table" rel="nofollow">http://en.wikipedia.org/wiki/Hash_table</a></p>
  
  <p>I was looking at the wiki and here are the steps to find the table index. </p>
  
  <pre><code>hash = hashfunc(key) // calculate hash value.
  index = hash % array_size // calculate index value through modulus. 
  </code></pre>
  
  <p>But it seems the way it is performed in Java is quite different. </p>
  
  <pre><code>static int hash(int h) {
     h ^= (h &gt;&gt;&gt; 20) ^ (h &gt;&gt;&gt; 12);
     return h ^ (h &gt;&gt;&gt; 7) ^ (h &gt;&gt;&gt; 4);
  }
  
  static int indexFor(int h, int length) {
     return h &amp; (length-1);
  }
  </code></pre>
  
  <p>The indexFor method which calculates the table index seems to be different. Can anyone add some light on this.</p>
  
  <p><strong>Update:</strong></p>
  
  <p>Hashing algorithim might vary accordingly, but the way we calculate the table index should be even if i am not wrong, but i see a conflict in what wiki does and the way java does?.</p>
  
  <p><strong>Sample code to test:</strong></p>
  
  <pre><code>import java.util.HashMap;
  import java.util.Iterator;
  import java.util.Map;
  
  public class Test {
  
      public static void main(String args[]) {
          Map&lt;String, String&gt; m = new HashMap&lt;String, String&gt;();
          m.put("Shane", null);
          Iterator&lt;String&gt; itr = m.keySet().iterator();
          while (itr.hasNext()) {
              String key = itr.next();
              int hash = hash(key.hashCode());
              System.out.println("&amp;&amp;&amp; used" + "table[" + (hash &amp; 15) + "]=" + key);
              System.out.println("%%% used" + "table[" + (hash % 15) + "]=" + key);
          }
      }
  
      static int hash(int h) {
          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>
  
  <p><strong>Output:</strong></p>
  
  <pre><code>&amp;&amp;&amp; usedtable[14]=Shane
  %%% usedtable[8]=Shane
  </code></pre>
  
  <p>Run the above program and you could see the table index is different when i use % and table index is different when i use &amp;. </p>