HashMap源码解析——基于jdk11
插入流程
首先我们从put方法说起:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
继续往下看putVal方法:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//如果table为空就初始化一个table n为table的长度
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//如果数据将要存放在数组的位置为空 那么就把该值的放在数组上
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//如果key已经存在, e = 存在的值
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
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);
//如果一个节点的元素太多 这个节点使用红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果key已经存在, e = 存在的值
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//e != null,说明存在相同的key
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)
resize();
afterNodeInsertion(evict);
return null;
}
获取流程
首先看看
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 ((tab = table) != null && (n = tab.length) > 0 &&
//找到链表的头
(first = tab[(n - 1) & hash]) != null) {
//如果链表头就是要找的key 返回结果
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
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;
}