HashMap之put
前提:
- jdk1.8之前HashMap的存储方式:链表+hash
- jdk1.8以后中HashMap的存储方式:链表+hash+红黑树算法
业务逻辑整理
- 1,判断当前map是否为空的,如果是则初始化。
- 2,判断当前key的hash是否存在map中,
- 2.1,如果不存在则直接添加对象当map中
- 2.2,如果存在
- 2.2.1,如果第一个的key与put的key一致,则把一致的对象赋值给e
- 2.2.2,如果对象为红黑树存储方式,则把一致的对象赋值给e
- 2.2.3,否则(存储方式非红黑树)循环当前对象
- 2.2.3.1,如果key有一致的,则把一致的对象赋值给e
- 2.2.3.2,如果key没有一致的,则在尾部追加当前对象,赋值一个null给e
- 2.2.4,如果e不是空,onlyIfAbsent为false,或者e的value为空,则把新值覆盖原有的值
以下是详细注释
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
这个代码没啥意思,还是要看putVal方法
/**
* Implements Map.put and related methods
* 实现了Map.put及相关方法
* @param hash hash for key
* key的hash值
* @param key the key
* 键
* @param value the value to put
* 键对应的值
* @param onlyIfAbsent if true, don't change existing value
* onlyIfAbsent 如果是true, 不改变原有的值(如果键和已存在的键一致的情况下)
* @param evict if false, the table is in creation mode.
* evict 如果是false, 该表处于创建模式。
* @return previous value, or null if none
* 返回原来的值(如果键和已存在的键一致的情况下),否则返回null
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//tab:当前对象数组 p:当前key对应的对象 n:当前对象数组的大小 i:p位于tab的下标
Node<K,V>[] tab; Node<K,V> p; int n, i;
//1.1,tab = table 把原有的数据赋值给tab(其实是对象地址)
//1.2,n = tab.length tab(原table)的长度赋值给n
//1.3,如果原来的tab(原table)是空的,则初始化tab(原table)
if ((tab = table) == null || (n = tab.length) == 0)
//1.3.1,具体如何初始化的,请看其他文章
n = (tab = resize()).length;
//2.1,i = (n - 1) & hash 计算出当前key应该存放的位置(及i的下标),并赋值给i
//2.2,tab[i]赋值给p
//2.3,如果p是空的,这直接添加对象
if ((p = tab[i = (n - 1) & hash]) == null)
//2.3.1,创建对象,添加到tab的i下标下
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//3.1,如果第一个的key与put的key一致,则把一致的对象赋值给e
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//3.2,如果对象为红黑树存储方式,则把一致的对象赋值给e
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//3.3,否则(存储方式非红黑树)循环当前对象
else {
for (int binCount = 0; ; ++binCount) {
//3.3.1,e被赋值下一个,如果是空的,表示当前对象不包含有一样的key
if ((e = p.next) == null) {
//3.3.1.1,在当前对象下追加一个对象
p.next = newNode(hash, key, value, null);
//3.3.1.2,判断当前对象的长度是否超过8,如果是,则转换成红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//3.3.2 如果key有一致的,跳出循环,e已经在3.3.1赋值了
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//3.4,如果e不是空,onlyIfAbsent为false,或者e的value为空,则把新值覆盖原有的值
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;
}
其他相关资料
链接: HashMap源码分析目录