K - key 泛型V - value 泛型public class MyHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>
(1)所有的 hash 值相同的元素,放在同一个桶中 (2)新增时 2.1 hash 值相同,且 equals() 的,则认为相同,使用替换。 2.2 不同的,则使用链表,新增。 新增时,进行判断,如果 size() 超出阈值,且 hash 的位置有元素,则进行 rehash()
这样是为了避免 hash 的桶数太少,导致的查找性能下降。 个人觉得,现在觉得这种方式很浪费。 比如:容量=8 当 size=6 的时候可能就要进行 rehash (size gte 阈值,且 hash 的位置,已经存在元素。) 某种角度而言,这是没有必要的。 因为即使在同一个桶上的数据出现重复,如果桶中链表的数量小于8,其实遍历性能并不差。
优化思路:可以考虑将 rehash 的条件调整为,当前 hash 的桶位置有元素,且当前桶的链表数量已经达到了8。
rehash 的优化思路: 可以参考 redis,进行渐进式 rehash。
(3)hash 的简化 jdk 实现中,对于 null 值做了特殊处理。其实感觉没必要,直接 null 的 hash 为0,比较的时候认为相等即可。
HashMapAbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K,V>| 构造器和说明 |
|---|
MyHashMap() |
MyHashMap(int capacity)
初始化 hash map
|
MyHashMap(int capacity,
boolean debugMode)
初始化 hash map
|
| 限定符和类型 | 方法和说明 |
|---|---|
Set<Map.Entry<K,V>> |
entrySet() |
V |
put(K key,
V value)
存储一个值
|
V |
remove(Object key)
删除一个元素
(1)元素不存在,直接返回 null
(2)元素存在,移除元素,判断是否需要缩容
|
clear, clone, containsKey, containsValue, equals, get, hashCode, isEmpty, keySet, putAll, size, toString, valuesclear, compute, computeIfAbsent, computeIfPresent, containsKey, containsValue, equals, forEach, get, getOrDefault, hashCode, isEmpty, keySet, merge, putAll, putIfAbsent, remove, replace, replace, replaceAll, size, valuespublic MyHashMap()
public MyHashMap(int capacity)
capacity - 初始化容量public MyHashMap(int capacity,
boolean debugMode)
capacity - 初始化容量debugMode - 是否开启 debug 模式Copyright © 2020. All rights reserved.