JDK8中HashMap的put、putVal方法
程序员文章站
2022-03-10 18:34:32
...
文章目录
一、putVal插入键值对过程
二、代码注释
- put()方法:调用了putVal()方法,具体逻辑都是在putVal中进行实现
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
- putVal()方法:
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//当加入第一个元素时,map中并没有key-value,此时table为null
if ((tab = table) == null || (n = tab.length) == 0)
//使用resize函数生成tab[]数组
n = (tab = resize()).length;
//(n - 1) & hash 相当于对将hash % n,根据hash得到桶的索引
if ((p = tab[i = (n - 1) & hash]) == null)
//当桶内没有元素的时候,实例化一个元素作为桶的第一个元素
tab[i] = newNode(hash, key, value, null);
else {//当桶内有元素时候,就需要解决hash冲突问题了
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//桶内的第一个元素的key值与新加入key-value的key相同的时候,用e指向p(仅仅指向)
e = p;
else if (p instanceof TreeNode)
//如果此时桶内已经树化,使用putTreeVal方法加入元素,若存在相同的key的元素,则将引用返回
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
//bitCount大于树化的阈值,转化为红黑树
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
//桶内存在元素的key值与新加入key-value的key相同的时候,用e指向p(仅仅指向)
break;
p = e;
}
}
//通过上面的code,若map中已经存在相同的key,
//我们则将Node<K,V> e指向该key-value,即Node(TreeNode是Node的子类)
//若e == null,则说明已经插入成功
//若e != null, 则将e.value作为旧值返回,将e.value设置为value
if (e != null) { // existing mapping for key
V oldValue = e.value;
//putVal中的参数。若onlyIfAbsent为null或者oldValue为空时才替换,
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//插入后大于阈值,使用resize()进行调整
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
上一篇: 北航 机试 简约版八皇后