在java中实现hashmap数据结构

时间:2014-03-06 04:57:09

标签: java hash hashmap hashtable collision-detection

我正在进行一项技术测试,下面给出了问题陈述,我没有得到我必须做的事情,请通过提供一些示例代码来帮助我。

Implement a hash-map data structure from scratch , where both key and value are of string data type.
The details of how a hash works can be found in Chapter 11 of the book "Introduction to
Algorithms" by Cormen, Leiserson, Rivest. You should also refer to Section 3.7 of "The
Algorithm Design Manual" by Steven Skiena. For the required hash-map implementation,
the following conditions hold true:
1. The key is made up of lower-case english alphabets only (a,b,c...z). It can be of any
length.
2. Values are of string data type.
3. The hash function to be used is the one given in Section 3.7 of Skiena.
4. Choose a suitable size of the hash-map, that is, the number of buckets. It should be
greater than 100.
4. Collisions will be resolved using Chaining. Doubly linked lists will be used to store
colliding entries.
You will have to implement the following operations on the hash-map:
a. Create an empty hash-map.
b. Insert a (key, value) pair into the hash-map.
c. Delete a (key) from the hash-map (if present).
d. Search for a (key) in the hash-map, and if present return its value. Else return null.

Thanks in advance.

1 个答案:

答案 0 :(得分:19)

如果我用英语解释HashMaps,我相信它会更有帮助。

什么是HashMap?

HashMap是一种能够将某些键映射到某些值的数据结构。键和值可以是任何东西。例如,如果我正在制作游戏,我可能会将每个用户名链接到朋友列表,由字符串列表表示。

为什么要使用HashMap?

HashMaps比数组和链接列表更快地检索数据。排序数组可以使用二进制搜索在O(log n)中找到特定值。但是,HashMap可以检查它是否包含O(1)中的特定键。所有密钥必须是唯一的。

HashMaps如何运作?

HashMaps在后台使用数组。数组中的每个元素都是另一个数据结构(通常是链表或二叉搜索树)。 HashMap使用键上的函数来确定将键的值放在数组中的位置。例如,如果我的HashMap接受字符串......可能的哈希函数可以是:

A. Return the ASCII value of the first letter.
B. Return the sum of the ASCII values of every character in the String.
C. Return the ASCII value of the last character in the String.

返回的值将决定值进入数组的索引。

但等等!这是一个问题!

返回的值可能超出了数组的范围。因此,我们应该按数组长度修改返回值。

return Math.abs(number%hashMapArray.length);

<强>冲突:

多个密钥是否可能使哈希函数生成相同的索引?是。例如,如果我们在字符串的哈希映射中使用上面显示的第一个哈希函数...任何两个以相同字母开头的字符串将被赋予相同的数组索引。

这称为碰撞。

我们如何处理碰撞?

一种碰撞处理技术称为链接。由于数组中的每个元素都是链表(或类似的数据结构),因此具有相同散列值的多个键将放在同一个链表或&#34; bucket&#34;中。之后,哈希映射能够通过使用散列函数计算散列码来检索值,并搜索特定链接列表以查看它是否包含具有相同键的值。

必须编写好的哈希函数以避免冲突。

链接的优势:

-Array无法溢出

-Data可以轻松删除

链接的缺点:

- 如果存储桶包含很长的链接列表,可能会遇到性能损失。

桶数的总条目数称为加载因子。如果负载系数太低,则会浪费大量空间。如果负载系数太高,则会丢失散列的优势。对负载系数的良好折衷是.75