public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
这是HashMap的put方法的源代码
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 默认初始化容量 向左移位4=2^4 = 16
static final int MAXIMUM_CAPACITY = 1 << 30; 最大容量 向左移位30=2^30
static final float DEFAULT_LOAD_FACTOR = 0.75f; 当前容量的极限比75%,用于扩展容量
static final int TREEIFY_THRESHOLD = 8; 链表节点>8,才能转红黑树
static final int UNTREEIFY_THRESHOLD = 6; 红黑树节点<=6,转链表
static final int MIN_TREEIFY_CAPACITY = 64; 红黑树初始容量
transient Node<K,V>[] table; 存放Mapping节点的位置,里面V可以是链表和红黑树
我们可以看到在put方法中它调用的是HashMap里面的putVal方法
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) //如果是刚创建的,则为tab赋一个初始容量为16的存放Mapping数组
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null) //该Map是否存在key,如果不存在,则为v新增链表
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)))) //该Map存在key,获取key的Value
e = p;
else if (p instanceof TreeNode) //key下的Value是一个红黑树
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else { //key下的Value是一个链表
for (int binCount = 0; ; ++binCount) { //从尾开始循环链表
if ((e = p.next) == null) { //如果头节点的Next为null,则新增一个节点
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st //如果链表大于8,则转换为红黑树
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 //HashMap不允许重复,所以新的值替换旧的值
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold) //如果是新增,则key增加,超过CAPACITY*LOAD_FACTOR,则重新散列
resize();
afterNodeInsertion(evict);
return null;
}
这是这个方法的源代码