我们都知道HashMap的底层结构是数组+链表(红黑树),初始大小是16,那这个16指的是数组的大小还是HashMap的整个的容量的大小呢。
如果是数组大小为16,是不是意味着当数组被占用到16*0.75=12个的时候就需要为数组扩容了。
如果是整个Map的大小,那么就是map.size()>12的时候就需要扩容了。
通过翻看源码结论是:
根据table.length * loadFactor=threshold;
扩容判断是 键值对数量(size)>threshold
查看类中定义的属性
private static final long serialVersionUID = 362498820763181265L;
//默认初始容量-必须是2的幂。
static final int DEFAULT_INITIAL_CAPACITY = 1<<4;
//最大容量 2e30
static final int MAXIMUM_CAPACITY =1<<30;
//默认加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//链表的阈值,超过这个值需要转成树
static final int TREEIFY_THRESHOLD = 8;
//树的大小小于这个值时,会从树转为链表
static final int UNTREEIFY_THRESHOLD = 6;
//树化条件,table.length小于64不会树化
static final int MIN_TREEIFY_CAPACITY = 64;
//存放数据的数组
transient HashMap.Node<K, V>[] table;
//存放数据的链表
transient Set<Entry<K, V>> entrySet;
//该映射中包含的键值映射数量
transient int size;
//这个HashMap结构被修改的次数
transient int modCount;
//需要扩容的阈值(capacity * loadfactor)
int threshold;
//装载因子
final float loadFactor;
hash方法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
该方法是将hashCode的高16位于低16异或,官网解释是为了减少碰撞。
才疏学浅,不会推导。
tableSizeFor
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;
}
该方法计算了table数组大小只能是2的n次幂
构造方法
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);
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
四个构造方法,除了最后一个,其他三个都没有初始化数组。只有在put的时候才会初始化table。
第一个构造方法,说明了,table的最大空间<=2e30, 装载因子>0
put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
这是我们经常使用的方法。他调用的是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;
//1.tab指向table,如果数组大小为空,则调用resize方法,并返回数组长度n。
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//计算要插入的键值在数组中的下标i,并判断该节点有没有数据,如果没有直接将键值放到该节点。(table.length-1)&hash 应该比取余的效率高 (此方法只适用于除数为2eN)
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//如果p=table[i]存在数据
Node<K,V> e; K k;
//存在的数据和要插入的数据的key相等,e=p
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//key不相等,hash冲突,当前节点p已经树化,调用 putTreeVal添加数据
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//key不相等,hash冲突,当前节点p没有树化,调用 putTreeVal添加数据
//binCount用来记录当前链表的长度
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;
}
}
if (e != null) { // existing mapping for key
//单纯的替换值,hashMap的修改次数不会增加
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
//返回oldValue
return oldValue;
}
}
//hashMap被修改次数+1
++modCount;
//键值数量+1,大于阈值执行resize()方法
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
reSize()方法
final Node<K,V>[] resize() {
//旧表数组
Node<K,V>[] oldTab = table;
//旧的数组长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//旧的阈值
int oldThr = threshold;
int newCap, newThr = 0;
//旧table已经初始化
if (oldCap > 0) {
//如果 数组长度已经大于 2e30,那么不载扩容,阈值也等于2e30
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//新的数组长度小于 2e30,
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults 第一次放值
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {//这什么时候会触发没看懂??
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
//创建新的数组
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}