HashTables如何处理碰撞? [英] How do HashTables deal with collisions?

查看:493
本文介绍了HashTables如何处理碰撞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学位课上听说,如果新的Key条目与另一个条目冲突, HashTable 会在下一个可用存储桶中放入一个新条目。



如果在使用碰撞密钥调用一个碰撞时发生这种碰撞,那么 HashTable 如何仍然返回正确的值? / p>

我假设 Keys String 类型并且 hashCode()返回由Java生成的默认值。



如果我实现自己的散列函数并使用它作为查找表的一部分(即 HashMap 字典),处理碰撞的策略是什么?



我甚至看过有关素数的注释! Google搜索中的信息不太明确。

解决方案

哈希表以两种方式之一处理冲突。



选项1:让每个存储桶包含一个链接到该存储桶的元素的链接列表。这就是错误的哈希函数可以使哈希表中的查找非常慢的原因。



选项2:如果哈希表条目全部填满则哈希表可以增加它拥有的桶的数量,然后重新分配表中的所有元素。哈希函数返回一个整数,哈希表必须获取哈希函数的结果,并根据表的大小对其进行修改,以确保它能够进入存储区。因此,通过增加大小,它将重新运行并运行模数计算,如果幸运的话,可以将对象发送到不同的桶。



Java同时使用选项1和2它的哈希表实现。


I've heard in my degree classes that a HashTable will place a new entry into the 'next available' bucket if the new Key entry collides with another.

How would the HashTable still return the correct Value if this collision occurs when calling for one back with the collision key?

I'm assuming that the Keys are String type and the hashCode() returns the default generated by say Java.

If I implement my own hashing function and use it as part of a look-up table (i.e. a HashMap or Dictionary), what strategies exist for dealing with collisions?

I've even seen notes relating to prime numbers! Information not so clear from Google search.

解决方案

Hash tables deal with collisions in one of two ways.

Option 1: By having each bucket contain a linked list of elements that are hashed to that bucket. This is why a bad hash function can make lookups in hash tables very slow.

Option 2: If the hash table entries are all full then the hash table can increase the number of buckets that it has and then redistribute all the elements in the table. The hash function returns an integer and the hash table has to take the result of the hash function and mod it against the size of the table that way it can be sure it will get to bucket. So by increasing the size, it will rehash and run the modulo calculations which if you are lucky might send the objects to different buckets.

Java uses both option 1 and 2 in its hash table implementations.

这篇关于HashTables如何处理碰撞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆