static final float DEFAULT_LOAD_FACTOR = 0.75f; //负载因子
static final int MAXIMUM_CAPACITY = 1 << 30; //hash表最大容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 //默认的容量
static final int TREEIFY_THRESHOLD = 8 当链表的长度超过8,才有机会树化
static final int MIN_TREEIFY_CAPACITY = 64; //当hash表的总容量超过64才会进行树化
- 构造方法
使用无参构造时,默认负载因子= static final float DEFAULT_LOAD_FACTOR = 0.75f;
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
- 第一次put
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
- 在resize()初始化
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
- 根据hash值求出下标,并且将找出首节点,或者创建首节点
if ((p = tab[i = (n - 1) & hash]) == null) //如果数组下标第一个节点为空,就新建节点,如果不为空,就将这个节点赋值给p节点
tab[i] = newNode(hash, key, value, null);
判断几种hash冲突情况
Node<K,V> e;//临时节点 K k;//当前 key
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k)))) //如果首节点的key和hash都等于当前插入的key,就将原来头节点赋值给临时节点,下面会做覆盖操作
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;
}
}
- 覆盖key
if (e != null) { // existing mapping for key 存在相同的key,覆盖
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value; //将新的value赋值给e节点
afterNodeAccess(e); //覆盖
return oldValue;
}
}
++modCount; //统计修改次数
if (++size > threshold) //判断容量是否超过临界值,如果超过执行扩容。
resize();
afterNodeInsertion(evict);