【问题标题】:Implementation of hashmap data structure in java [closed]java中hashmap数据结构的实现[关闭]
【发布时间】:2014-04-08 13:11:48
【问题描述】:

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

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.

【问题讨论】:

  • 首先从第11章开始,看看java的实现。
  • 您在问题中包含的说明准确地描述了您需要做什么。阅读所引用的书籍/文件。阅读 HashMap 的 javadoc 以了解这些方法的作用。
  • 这个问题似乎是题外话,因为它表明作者没有尝试理解和解决问题。

标签: java hash hashmap hashtable collision-detection


【解决方案1】:

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

什么是 HashMap?

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

为什么要使用 HashMap?

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

HashMaps 是如何工作的?

HashMap 在后台使用数组。数组中的每个元素都是另一种数据结构(通常是链表或二叉搜索树)。 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函数生成同一个索引吗?是的。例如,如果我们在字符串的哈希映射中使用上面显示的第一个哈希函数...任何两个以相同字母开头的字符串都将被赋予相同的数组索引。

这称为碰撞。

我们如何处理碰撞?

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

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

链接的优点:

-数组不能溢出

-数据可以轻松删除

链接的缺点:

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

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

【讨论】:

  • 我还是不明白,所以实际上最小的 HashMap 是 3 个组件的东西:1 个常规数组单元 -> 在 LinkedList(例如)内 -> 在每个链表单元内 1 个名为 Entry 的类的实例(例如)有 2 个字段 key 和 value 。我说的对吗?
  • 是的,我相信它是这样工作的。
  • 只是为了说清楚..第二个答案中的数组是指 ArrayList 而不是“数组”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多