public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
其中传入的hash函数
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
具体实现put的方法 扩容函数,会重新计算hashmap里面对应元素的hash并放到不同的元素上
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)
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
/ This field is used to make iterators on Collection-views of the HashMap fail-fast.
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
大概流程总结下来就是 1.如果当前数组是空就初始化或者扩容 2.如果计算出来的数组下标中没有值,那么直接插入 3.如果hash冲突,判断是否为红黑树结构,如果是的那么插入到红黑树中,如果不是则遍历链表,插入到链表中,插入之后会判断链表长度是否》=8且数组长度>=64,如果是则会转换为红黑树结构 4.如果其中存在一摸一样的key那么就修改值 5.最后判断数组容量是否大于阈值,如果是的,那么就扩容
|