您的位置:首页 > 编程语言 > Java开发

HashMap源码注解 之 put()方法(六)

2016-04-24 14:14 701 查看
注意 , 本文基于JDK 1.8



HashMap#put()

/**
* 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);
}

/**
* 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;
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;
}


put方法将KV放在map中。如果,该key已经存放在map中,则用新值直接替换旧值。

put的返回值:如果该key已经存放在map中,则返回其映射的旧值;如果不存在,则返回null,表示没有该key对应的映射(也有可能原来的映射是key-null)。

当new HashMap实例时,并没有初始化其成员变量
transient Node<K,V>[] table;
,也就是说并没有为table分配内存。只有当put元素时才通过resize方法对table进行初始化。因此,建议先看HashMap#resize()方法 HashMap源码注解 之 resize()方法(七)

put方法分两种情况,bucket是以链表形式存储的还是以树形结构存储的。如果是key已存在则修改旧值,并返回旧值,如果key不存在,则执行插入操作,返回null。如果是插入操作还要modCount++。当如果是链表存储时,如果插入元素之后超过了TREEIFY_THRESHOLD,还要进行树化操作。

注意:put操作,当发生碰撞时,如果是使用链表处理冲突,执行的尾插法。这个跟ConcurrentHashMap不同,ConcurrentHashMap执行的是头插法。因为,其HashEntry的next是final的。

put操作的基本流程:

(1)通过hash值得到所在bucket的下标,如果为null,表示没有发生碰撞,则直接put

(2)如果发生了碰撞,则解决发生碰撞的实现方式:链表还是树。

(3)如果能够找到该key的结点,则执行更新操作,无需对modCount增1。

(4)如果没有找到该key的结点,则执行插入操作,需要对modCount增1。

(5)在执行插入操作时,如果bucket中bin的数量超过TREEIFY_THRESHOLD,则要树化。

(6)在执行插入操作之后,如果size超过了threshold,这要扩容。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jdk hashmap 源码 注解 put