/**
*
* @param key 需要存入数组中的元素键
* @param value 需要存入数组中的元素值
* @return 返回被存入的元素值
*/
public V put(K key, V value) {
return this.putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
//临时变量table用于存储Hashtable中的table元素数组
HashMap.Node[] tab;
//table数组的长度
int n;
//当数组没有被初始化时
if ((tab = this.table) == null || (n = tab.length) == 0) {
//第一次调用resize函数将数组初始化,并返回table的长度
n = (tab = this.resize()).length;
}
//当数组已经被初始化
Object p;
int i;
//如果当前元素的hash位置上不存在元素
//则将该元素构造为node对象直接存入table的当前位置
if ((p = tab[i = n - 1 & hash]) == null) {
tab[i] = this.newNode(hash, key, value, (HashMap.Node)null);
} else {
//如果当前位置存在元素,则表示发生hash冲突
Object e;
Object k;
//如果当前元素的hash值与key值均与需要被存入的元素相同,则直接返回该元素
if (((HashMap.Node)p).hash == hash && ((k = ((HashMap.Node)p).key) == key || key != null && key.equals(k))) {
e = p;
}
//当前table位置为红黑树,则以红黑树的方式插入元素.
else if (p instanceof HashMap.TreeNode) {
e = ((HashMap.TreeNode)p).putTreeVal(this, tab, hash, key, value);
}
//当前table位置为链表.
else {
//临时变量储存该链表的长度
int binCount = 0;
//循环后移
while(true) {
//当前元素是尾元素
if ((e = ((HashMap.Node)p).next) == null) {
//将该元素插入链表尾部
((HashMap.Node)p).next = this.newNode(hash, key, value, (HashMap.Node)null);
//当该链表长度大于8时,将链表树化
if (binCount >= 7) {
this.treeifyBin(tab, hash);
}
break;
}
//当循环途中发现了与需要插入的元素相同的元素,直接退出循环,并返回当前元素
if (((HashMap.Node)e).hash == hash && ((k = ((HashMap.Node)e).key) == key || key != null && key.equals(k))) {
break;
}
p = e;
//将链表的元素个数自增,用于判断是否需要树化
++binCount;
}
}
//当查找到元素时,返回查找到的元素
if (e != null) {
//获取强转后的value值,并返回
V oldValue = ((HashMap.Node)e).value;
//如果原来的value不为空,则覆盖原来的value
if (!onlyIfAbsent || oldValue == null) {
((HashMap.Node)e).value = value;
}
this.afterNodeAccess((HashMap.Node)e);
return oldValue;
}
}
//将table数组储存的元素个数自增
++this.modCount;
//当元素个数大于最大负载容量时,重新将table初始化,分配元素
if (++this.size > this.threshold) {
this.resize();
}
this.afterNodeInsertion(evict);
return null;
}