1.put
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
//通过key生成hash后,调用putVal方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
}
2.putVal
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果table为null或者长度为0,则调用resize初始化table
if ((tab = table) == null || (n = tab.length) == 0){
n = (tab = resize()).length;
}
//key -> hash -> i
if ((p = tab[i = (n - 1) & hash]) == null){//如果table[i]的元素为null
tab[i] = newNode(hash, key, value, null); //放入table[i]
} else {
Node<K,V> e; K k;
//这时候的p是table[i]
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k)))){
//hash 相等,key相等,要放在table[i]处
e = p;
} else if (p instanceof TreeNode){//不能放在table[i]
//是红黑树
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
} else {//是链表
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {//如果一直没有找到一个hash和key相等的
p.next = newNode(hash, key, value, null);//添加到最后
//判断链表长度是否达到了大于或者等于8
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)))){
//hash 相等,key相等
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){如果数据个数大于threshold
resize(); //扩容
}
afterNodeInsertion(evict);
return null;
}
}
3.流程图