是否有不同的方法来计算HashMap中的表索引

http://en.wikipedia.org/wiki/Hash_table

我正在查看wiki,以下是查找表索引的步骤。

hash = hashfunc(key) // calculate hash value. index = hash % array_size // calculate index value through modulus. 

但它似乎在Java中的表现方式却截然不同。

 static int hash(int h) { h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } static int indexFor(int h, int length) { return h & (length-1); } 

计算表索引的indexFor方法似乎不同。 任何人都可以对此加以说明。

更新:

散列算法可能会有相应的变化,但我们计算表索引的方式应该是即使我没有错,但我看到wiki和java的做法有什么冲突?

要测试的示例代码:

 import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Test { public static void main(String args[]) { Map m = new HashMap(); m.put("Shane", null); Iterator itr = m.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); int hash = hash(key.hashCode()); System.out.println("&&& used" + "table[" + (hash & 15) + "]=" + key); System.out.println("%%% used" + "table[" + (hash % 15) + "]=" + key); } } static int hash(int h) { h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } } 

输出:

 &&& usedtable[14]=Shane %%% usedtable[8]=Shane 

运行上面的程序,当我使用%时,你可以看到表索引是不同的,当我使用&时,表索引是不同的。

但它似乎在Java中的表现方式却截然不同。

实际上它们完全一样。

 hash = hashfunc(key) // calculate hash value. 

是相同的

 hash = hash(key.hashCode()); 

 index = hash % array_size (assumes the hash is unsigned) 

是相同的

 return h & (length-1); 

因为长度是2的幂。