字典
字典,又称为符号表( symbol table)、关联数组( associative array)或映射( map),是一种用于保存键值对( key-value pair )的抽象数据结构。
在字典中,一个键( key)可以和一个值( value)进行关联(或者说将键映射为值),这些关联的键和值就称为键值对。
字典中的每个键都是独一无二的,程序可以在字典中根据键查找与之关联的值,或者通过键来更新值,又或者根据键来删除整个键值对,等等。
字典实现
哈希表
![](https://img-blog.csdnimg.cn/img_convert/caf805e8083824c9276870533e3e794f.png)
![](https://img-blog.csdnimg.cn/img_convert/31c149eaec0329e06d9ed4c12affd729.png)
哈希表节点
![](https://img-blog.csdnimg.cn/img_convert/44a0d6c9297de8482171e008fb28d37b.png)
字典
![](https://img-blog.csdnimg.cn/img_convert/a64145085c283a2fca8ee0a62f3fc5c5.png)
![](https://img-blog.csdnimg.cn/img_convert/b4826a64cc7af59aee8f1f4e6d15e431.png)
哈希算法
![](https://img-blog.csdnimg.cn/img_convert/19ff4a974aa0e7493414cafa20f800e7.png)
![](https://img-blog.csdnimg.cn/img_convert/3a9c638a36121f2a5fcf1dc7c97f3d8e.png)
解决键冲突
当有两个或以上数量的键被分配到了哈希表数组的同一个索引上面时,我们称这些键发生了冲突(collision )。
Redis 的哈希表使用链地址法( separate chaining)来解决键冲突,每个哈希表节点都有一个next指针,多个哈希表节点可以用next 指针构成一个单向链表,被分配到同一个索引上的多个节点可以用这个单向链表连接起来,这就解决了键冲突的问题。
举个例子,假设程序要将键值对k2和v2添加到图4-6所示的哈希表里面,并且计算得出k2的索引值为2,那么键k1和k2将产生冲突,而解决冲突的办法就是使用next指针将键k2和k1所在的节点连接起来,如图4-7所示。
因为dictEntry节点组成的链表没有指向链表表尾的指针,所以为了速度考虑,程序总是将新节点添加到链表的表头位置(复杂度为O(1)),排在其他已有节点的前面。
![](https://img-blog.csdnimg.cn/img_convert/112eb4ba7417b8615c2f70cb9c7b0c77.png)
Rehash
![](https://img-blog.csdnimg.cn/img_convert/e6517b256abe89b9f7f3e58e82b19136.png)
![](https://img-blog.csdnimg.cn/img_convert/123d586bbc46b25e8fe9462b15d4342a.png)
![](https://img-blog.csdnimg.cn/img_convert/f37b753c65b793f83f872d3536cd3738.png)
![](https://img-blog.csdnimg.cn/img_convert/1a38385be157738c025a1875775900d1.png)
![](https://img-blog.csdnimg.cn/img_convert/ce263bb63d99d6fad2ab6e900e07a494.png)
![](https://img-blog.csdnimg.cn/img_convert/21aec80121128b7ad5070eb5ed7faee3.png)
渐进式rehash
![](https://img-blog.csdnimg.cn/img_convert/c107e40d3640a93a4b1a44eb5ea1fe31.png)
![](https://img-blog.csdnimg.cn/img_convert/087b3d0fac1585adbfc9066b89db6577.png)
![](https://img-blog.csdnimg.cn/img_convert/e9e7743fd30548e1fa6774d3bfbb8603.png)
![](https://img-blog.csdnimg.cn/img_convert/9ba0a3424e1be71b5deda8fa2d38a924.png)
![](https://img-blog.csdnimg.cn/img_convert/42abe3cc6be32d29be37bbc7c8d1ffc8.png)
字典API
![](https://img-blog.csdnimg.cn/img_convert/01737a45633705bb41610e3b6eae322a.png)