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方法)java
【6】(n-1)&hash查找hash表中的数组索引,保证查找的位置不会大于数组长度,相似于求余查询索引数组
【6】【7】经过计算的索引在数组中位置数据为null,则在该索引位置建立新的节点数据结构
【9-35】获取已存在的节点app
【9-11】要查询的节点位于数组或者说链表的第一个this
【13-14】若是是红黑树,则调用红黑树中的put方法获取要查询的节点code
【16-27】链表查询节点索引
【19-20】若是某一个链表的节点数>=TREEIFY_THRESHOLD-1,则改成红黑树存储hash
总结:io
hashmap的数据结构为hash表,具体结构以下:
table
第一行为数组,经过求hash值与数组的大小的位运算求得索引定位数据;添加数据的时候,检查每一个桶的数据大小,若是超过8(默认)个,则将链表修改成红黑树存储;添加完数据检查数组大小,若有必要,重置数组大小(resize())