通俗解析
###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;
// 如果数组为空或者长度为0,扩容,一般不会为0,除非new的时候特意初始化为0
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 如果当前key的hash在数组中尚不存在,就直接new一个node放进去
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 如果当前key的hash已经存在且key值也相同,则将value覆盖进去
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
// 如果hash存在但是key不同,且node已经是TreeNode(红黑树类型的节点),则加到树里
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 如果不是treeNode,则还是链表,要往后追加
for (int binCount = 0; ; ++binCount) {
// 从链表头往下遍历
if ((e = p.next) == null) {
// 如果已经到了链表尾,则将当前新node追加到尾部
p.next = newNode(hash, key, value, null);
// 如果追加完这个,链表长度会达到8个,则把链表改成用TreeNode(红黑树),并且结束遍历
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;
}
}
// 前面只是取到要赋值的node,这里是真正把value赋值进来
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// modeCount的作用是在使用迭代器遍历时保证数据不被修改:http://blog.youkuaiyun.com/u012926924/article/details/50452411
++modCount;
// size增长触发扩容
if (++size > threshold)
resize();
// 这是给LinkedHashMap用的
afterNodeInsertion(evict);
return null;
}