【发布时间】:2011-12-25 08:35:04
【问题描述】:
我正在尝试使用双散列将字符串键散列到散列表中。我做了类似的事情:
protected int getIndex(String key) {
int itr = 0,
size = this.values.length,
index1,
index2,
index = 0;
do {
// do double hashing to get index for curr [itr] (iteration)
index1 = Math.abs(key.hashCode()) % size;
index2 = size - ((key + key + "#!@").hashCode() % size); # trying very hard to eliminate clash, but still fails ... TA and AT gets index 2 when size = 5
index = (index1 + (itr * index2)) % size;
// if itr > set threshold, exit
itr++;
if (itr > 200) {
index = -1;
break;
}
// once index found, exit loop
} while (index > 0 && this.keys[index] != null && !this.keys[index].equals(key));
return index;
}
主要部分是do 之后的第 3 行。我可以说如果我使用Double Hashing,它应该消除碰撞的可能性吗? size 是我的哈希表的唯一键的总可能值
【问题讨论】:
-
AFAIK 真的很难找到一种可以消除碰撞的算法。正如您所说,哈希表在发生冲突时使用重新散列/双重散列。但是当涉及到 Dictionary 时,它使用链接来避免冲突。现在,与重新散列/双重散列相比,链接中的查找时间将相对较少。简而言之,如果您能够实现一个没有冲突的算法,那就太好了。否则,我个人建议您使用链接(冲突解决)而不是重新散列。
-
我不会修改
index1和index2的大小。当你丢弃大量信息时。您只需要 %size 最终值。特别是,index2很有可能为 0。
标签: java hash hashtable double-hashing