HashMap (jdk1.8)
特征:
-
懒汉式(数组长度最小16,负载因子0.75)
-
Node数组+链表+红黑树
-
链表转化成红黑树条件 (链表长度为8,数组长度为64)
Node节点的结构
Node节点的hash值由key在进行hash所得的值
Hash函数
hash函数获得hash值
hash函数目标:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
为什么要右移16位?
其实是为了减少碰撞,进一步降低hash冲突的几率。int类型的数值是4个字节的,右移16位异或可以同时保留高16位于低16位的特征
为什么要异或运算?
首先将高16位无符号右移16位与低十六位做异或运算。如果不这样做,而是直接做&运算那么高十六位所代表的部分特征就可能被丢失 将高十六位无符号右移之后与低十六位做异或运算使得高十六位的特征与低十六位的特征进行了混合得到的新的数值中就高位与低位的信息都被保留了 ,而在这里采用异或运算而不采用& ,| 运算的原因是 异或运算能更好的保留各部分的特征,如果采用&运算计算出来的值会向1靠拢,采用|运算计算出来的值会向0靠拢
通过hash值计算Node数组中的下标
tab[(length - 1) & hash];
length是2的倍数,length-1低位都是0,与上hash能交hash值映射到length长度
相当于效率很高的取模
HashMap的put流程
注意内存空间开辟是饿汉式
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//底层存储数据的数组tab为空,进行第一次扩容,同时初始化tab
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//计算要存储数据的下标index,如果当前位置为null,直接插入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//tab[i]的首个元素就是key,直接覆盖
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//tab[i]为TreeNode,进行红黑树的插入
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//链表遍历
else {
for (int binCount = 0; ; ++binCount) {
//尾插法
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//链表长度大于8,转换为红黑树进行处理
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//找到已经存在的key,直接覆盖
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//数据插入完成,size超过了扩容的阀值(容量*负载因子),进行扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
HashMap的get流程
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// 只有在存储数组已经存在的情况下进入这个 if
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// first 是获取的坐标上元素
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
// key 相同,说明first是想要的元素,返回
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
// 如果是红黑树,从红黑树中查找结果
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
// 循环遍历查找
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
get 方法流程总结。
-
计算 key 的 hash 值。
-
如果存储数组不为空,且计算得到的位置上的元素不为空。继续,否则,返回 Null。
-
如果获取到的元素的 key 值相等,说明查找到了,返回元素。
-
如果获取到的元素的 key 值不相等,查找 next 节点的元素。
-
- 如果元素是红黑树,在红黑树中查找。
- 不是红黑树,遍历 next 节点查找,找到则返回。
参考:Java笔记虾与逆流而上的龟的博客,感谢!