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;
if ((p = tab[i = (n - 1) & hash]) == null)
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;
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;
}
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;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
【4】【5】如果原始的节点数组为空或者节点数目=0,则重置数组大小为默认值(resize方法)
【6】(n-1)&hash查找hash表中的数组索引,保证查找的位置不会大于数组长度,类似于求余查询索引
【6】【7】通过计算的索引在数组中位置数据为null,则在该索引位置创建新的节点
【9-35】获取已存在的节点
【9-11】要查询的节点位于数组或者说链表的第一个
【13-14】如果是红黑树,则调用红黑树中的put方法获取要查询的节点
【16-27】链表查询节点
【19-20】如果某一个链表的节点数>=TREEIFY_THRESHOLD-1,则改为红黑树存储
总结:
hashmap的数据结构为hash表,具体结构如下:
第一行为数组,通过求hash值与数组的大小的位运算求得索引定位数据;添加数据的时候,检查每个桶的数据大小,如果超过8(默认)个,则将链表修改为红黑树存储;添加完数据检查数组大小,如有必要,重置数组大小(resize())