java - java中hashmap数据结构的实现

标签 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.

最佳答案

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

什么是 HashMap?

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

为什么要使用 HashMap?

HashMap 在检索数据方面比数组和链表快得多。排序后的数组可以通过二分查找在 O(log n) 中找到特定值。但是,HashMap 可以检查它是否包含 O(1) 中的特定键。所有 key 都必须是唯一的。

HashMap 如何工作?

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);

碰撞:

难道多个key不会让hash函数生成相同的索引吗?是的。例如,如果我们在字符串的 HashMap 中使用上面显示的第一个哈希函数......任何两个以相同字母开头的字符串都将被赋予相同的数组索引。

这称为碰撞。

我们如何处理碰撞?

一种碰撞处理技术称为链接。由于数组中的每个元素都是一个链表(或类似的数据结构),具有相同哈希值的多个键将被放置在同一个链表或“桶”中。之后, HashMap 能够通过哈希函数计算哈希码来检索值,并搜索特定的链表以查看它是否包含具有相同键的值。

必须编写一个好的散列函数来避免冲突。

链接的优势:

-数组不能溢出

-数据可以轻松删除

链接的缺点:

-如果桶包含非常长的链表,可能会影响性能。

条目总数与桶数之比称为负载因子。如果负载因子太低,就会浪费大量空间。如果负载因子太高,散列的优势就失去了。负载因子的一个很好的折衷是 .75

关于java - java中hashmap数据结构的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22215353/

相关文章:

java - Android 应用程序首选项中的值是否会自动保存?

algorithm - 客户端服务请求的隐式 "Authentication"

java - HashMap 优化的影响,将与每个条目关联的哈希代码缓存到其 get 方法

arrays - 给定一个哈希数组,如何用每个可能的组合创建一个哈希数组

php - 如果我从数据库中获取哈希值,password_verify 返回 false,但如果我复制并粘贴它,则返回 true

java - 如何根据类的值将类对象添加到hashMap?

java - 插入到 Hashmaps 的 Hashmap 中,Java

java - 如何从 Apache 服务器日志中解析 IP 地址?

java - Swift 新手 - 可失败的初始化器

java - 从内部类引用封闭实例