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) //哈希数组为空,或长度为0时,初始化数组resize()
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null) //数组长度-1&哈希值 == 哈希值%数组长度,用来计算元素的位置
tab[i] = newNode(hash, key, value, null); //如果计算出的位置上元素为空,则创建一个Node存储相应的值
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); //对链表操作次数大于等于8时,转为红黑树结构
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;
}
关于源码中的常量说明:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 哈希表默认长度 16 必须是2的倍数
static final int MAXIMUM_CAPACITY = 1 << 30; 最大长度
static final float DEFAULT_LOAD_FACTOR = 0.75f; 当哈希表被使用0.75时,会扩容,用一定的空间,换取查询效率
static final int TREEIFY_THRESHOLD = 8; 当链表长度等于8 转为红黑树
static final int UNTREEIFY_THRESHOLD = 6; 当树的节点个数为6时,转为链表