/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* 在第一次用的時候初始化扩劝,長度是2的冪
*/
transient Node<K,V>[] table;
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
// size大于這個值的時候 resize (capacity * load factor).
int threshold;
// 加載因子 默認0.75
final float loadFactor;
構(gòu)造函數(shù) 初始化值
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
put 方法 當(dāng)初始化完成后 第一次調(diào)用put方法簇秒,因為(table==null) 所以第一次put會resize()鱼喉,通過這次resize() threshold 即變?yōu)樵萾hreshold的loadFactor倍(默認0.75)
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 {
···
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}