Java 在HashMap中计算表索引有不同的方法吗
我正在查看wiki,下面是查找表索引的步骤Java 在HashMap中计算表索引有不同的方法吗,java,Java,我正在查看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
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);
}
计算表索引的index方法似乎有所不同。有没有人能解释一下
更新:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Test {
public static void main(String args[]) {
Map<String, String> m = new HashMap<String, String>();
m.put("Shane", null);
Iterator<String> 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
散列算法可能会相应地有所不同,但即使我没有错,我们计算表索引的方法也应该是正确的,但我发现wiki的做法与java的做法存在冲突
要测试的示例代码:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Test {
public static void main(String args[]) {
Map<String, String> m = new HashMap<String, String>();
m.put("Shane", null);
Iterator<String> 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());
return h & (length-1);
及
与
hash = hash(key.hashCode());
return h & (length-1);
因为长度是2的幂。你的确切问题是什么?你在维基百科中看到的公式只是检测散列键/索引的一种方法。这并不意味着总是这样。@LuiggiMendoza:看起来wiki中的一个和java代码中的一个在计算表索引时是不同的。问题是……从wikipedia中的链接来看,似乎您忘记阅读这一部分(我的):通常分两步完成:。注意:Java散列属于不常见的部分:)。还有一件事。您正在查看OpenJDK或HotSpot中的Java代码,其他JVM实现(如JRockit或IBM JVM)可能会使用完全不同的实现。谢谢Peter,我已经用示例测试代码更新了我的问题。。。你能解释一下吗?@Shane注意到
(长度-1)
,其中长度是2的幂i、 e.您需要将hash&15
与hash%16