HashMap 底层原理及源码分析
-
底层数据结构:数组+单向链表+双向链表+红黑树
-
JDK1.7 使用的是头插法 1.8后使用的是尾插法
-
HashMap 会有两种情况会进行扩容
第一种就是和数组长度相关 ,如果元素的个数大于默认阈值会进行扩容。第二种是和链表长度相关,如果某个链表长度大于8的时也可能会调用扩容方法 -
hash的时候并不会直接调用hashCode方法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
//右移16位 再进行异或运算
例如 h : 1001 0100 1010 0110 0011 1100 1000 0001
右移16位后 : 0000 0000 0000 0000 1001 0100 1010 0110
再进行异或 : 1001 0100 1010 0110 1010 1000 0010 0111
这样高位也参与了hash运算
}
- 与(&) : 两个是1才是1
- 异或(^):相同为0,不同为1
- 或(|) :只要有一个是1就是1
右移16位 再进行异或运算得到运算后的hashCode
初始化一个数组 Node[]=16 默认2的4次方
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i; //考虑到性能问题使用局部变量
//常用的变量赋值给局部变量 只需要从栈里面去拿 不用每次都从堆里拿,这样使用性能更优
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length; //tab = resize() 初始化一个数组容量为 16
if ((p = tab[i = (n - 1) & hash]) == null) //i = (n - 1) & hash 使用的是与操作(都为1则为1) 取决于二进制hash的后四位
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p; //如果key存在的话直接 goto A方法,将第一个节点的p赋值给e
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) { //如果第二个节点为空 直接break
//当真正转红黑树时 加上数组里的头节点 链表一共有9个节点
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//红黑树化
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//A方法
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;//更新新的值
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold) //threshold 扩容阈值 16*0.75=12
resize();
afterNodeInsertion(evict);
return null;
}
- 如果链表长度大于8 不一定会转换成红黑树 得先判断一下数组长度是否小于64,如果小于64会进行扩容处理
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//如果当前数组长度小于64 就不会转化为红黑树 直接扩容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
//将Node转化成TreeNode对象
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
//并且将单向链表改成双向链表
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
- put(k,v): 不管怎么样一定会更新value
- putIfAbsent(k,v): 如果key冲突,且原来key对应的值为null才会更新, 否则就不会更新value,如果key不冲突 重新生成新键值对