HashMap源码解析
1.属性
//数组默认的长度
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;//16
//数组允许的最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认的负载因子 当数组中的元素数量达到了数组的容量x负载因子时,对数组进行扩容
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//树化的条件1:链表的容量达到8
static final int TREEIFY_THRESHOLD = 8;
//树化的条件2:整个集合的元素达到64
static final int MIN_TREEIFY_CAPACITY = 64;
//反树化条件:当一个红黑树的元素减少到6时,将红黑树还原成单向链表
static final int UNTREEIFY_THRESHOLD = 6;
//充当两个作用 1.Map集合的Entry对象 2.链表的节点
static class Node<K,V> implements Map.Entry<K,V>{...}
//用来存放元素的数组
transient Node<K,V>[] table;
//记录map集合中键值对的数量
transient int size;
//扩容的临界值 就是数组容量x负载因子得到的值
int threshold;
//记录实际的负载因子
final float loadFactor;
2.无参构造方法
只会初始化负载因子
数组没有初始化,再第一次添加的时候初始化
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
3.有参构造方法
指定了数组的初始化容量,默认使用0.75作为负载因子,数组没有被初始化
public HashMap(int initialCapacity) {
//调用其他构造器 loadFactor为默认的负载因子
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)) //not a number 判断
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;//将指定的负载因子的值赋值给loadFactor属性
//扩容时会用到
this.threshold = tableSizeFor(initialCapacity);//得到一个不小于指定容量的最小的2的幂次方值赋值给threshold
}
tableSizeFor()
static final int tableSizeFor(int cap) {
//假设cap为13
int n = cap - 1;//n:12
//00000000 00000000 00000000 0001100
//右移一位: 00000000 00000000 00000000 0000110
//与n做|运算: 00000000 00000000 00000000 0001100
// 00000000 00000000 00000000 0001110
n |= n >>> 1;//n = n | n >>> 1 n-->14
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;//n-->15
//return n+1(16)
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
返回距离指定参数最近的2的整数次幂,例如7->8, 8->8, 9->16, 17->32 保证为2的幂次方
4.put
public V put(K key, V value) {
//hash(key)方法 如果传入的为null 返回0,否则按照指定的hashCode方法计算一个hash值
return putVal(hash(key), key, value, false, true);
}
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赋值给tab 为null时 还未初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length; //n为扩容之后的长度
/*通过n与hash(key)计算得到的hash值 &运算 得到一个小于等于n-1的一个数 用来计算存放的位置
如果为null(说明该位置上面没有元素)直接将元素添加到table中
*/
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//说明存放的位置有值 1.hash重复了 2.hash碰撞
else {
Node<K,V> e; K k;
//如果p的hash等于当前的hash值,并且key值相等
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
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); //尾插法,将该元素指向新的元素
/*
如果单前链表节点数大于等于8,链表结构转换成红黑树,
该方法里会有第二层判断(HashMap的容量大于等于64才进行转红黑树)
*/
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;//跳出循环
}/*
该位置上不止一个元素
判断如果hash值一样 并且key相同 直接覆盖
*/
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
/*
e!=null说明 发生了覆盖
则把以前的value替换成新value,并把老的值return回去
*/
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//上面的代码进行完还没有return就修改次数加一,判断是否需要扩容
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
5.resize()
final Node<K,V>[] resize() {
//创建一个新的数组用来接受 table(为原数组,首次初始化的时候为null)
Node<K,V>[] oldTab = table;
//旧数组容量 如果时初始化 默认为0, 反之就是table的容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//threshoul为阈值(临界值),默认构造器为0,有参构造器为:tableSizeFor(initialCapacity);
int oldThr = threshold;
//新的容量 新的阈值
int newCap, newThr = 0;
if (oldCap > 0) {//table扩容过
if (oldCap >= MAXIMUM_CAPACITY) { //容量大于最大容量时
threshold = Integer.MAX_VALUE; //阈值为最大的int值
return oldTab;
}//新的容量乘以二<最大容量 旧的容量(默认为16)>=默容量比较
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold //新的阈值为原来的2倍
}
//使用带有初始容量的构造器时,newcap为初始化得到的threshold
// this.threshold = tableSizeFor(initialCapacity);
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);
}
/*
新的阈值为0的时候 说明是带有初始容量的构造器
上面只为newCap赋值
新的阈值为 新的容量*转载因子
*/
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//将新的阈值赋值给threshold
threshold = newThr;