HashMap源码分析
最简单的一个例子
Map<String,String> map = new HashMap<String,String>();
map.put("a","a");
从构造函数开始分析:
static final float DEFAULT_LOAD_FACTOR = 0.75f;
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
接下来执行put函数
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
先看一下hash函数做了什么
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
分析下hash算法(h = key.hashCode()) ^ (h >>> 16)
hashCode的值是32位二进制
假设h得到的值是: 10010001 10010101 10110000 11110001
右移16位得到的值是: 00000000 00000000 10010001 10010101
异或(同为0,不同为1): 10010001 10010101 00100001 01100100
假设h得到的值是: 10010001 00000000 00000000 00000000
右移16位得到的值是: 00000000 00000000 00000000 10010001
异或(同为0,不同为1): 10010001 00000000 00000000 10010001
通过这种方式,可以提高1的分布变得相对均匀一些
为什么要变得相对均匀呢?我们接着看
查看putVal的函数
由于代码比较长,我这里分段来显示且直接在代码里进行解释
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//定义了一个Node数组,Node这个类里面包含了四个属性,hash值,Key,Value,指向下一个Node的指针
Node<K,V>[] tab; Node<K,V> p; int n, i;
//对table进行一个判空操作,table是一个Node数组
if ((tab = table) == null || (n = tab.length) == 0)
//如果为空则走resize()
n = (tab = resize()).length;
......(省略其余代码)
}
resize()函数
final Node<K,V>[] resize() {
//将table赋值给oldTab
Node<K,V>[] oldTab = table;
//oldCap为0
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//目前oldCap为0
....(省略部分代码)
else {
//赋值新的空间和新的阈值
//static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//DEFAULT_LOAD_FACTOR = 0.75f
//新的空间是16,新的阈值是12
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
....(省略部分代码)
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
//申请16大小的空间
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
....(省略部分代码)
return newTab;
}
回到putVal函数
此时n得到的值为16
....(省略部分代码)
//进行取余
if ((p = tab[i = (n - 1) & hash]) == null)
....(省略部分代码)
tab[i = (n - 1) & hash]单独抽出来解释
n = 16 二进制码: 0001 0000
n-1=15: 0000 1111
假设hash值是: 0000 0001
取余运算后的结果是: 0000 0001
当n是2的幂次方,减一后再去取余一定能保证,前面的都是0
这里就可以解决了一个问题,节约内存 而且进行与h操作的速度会很快
上面提到过为什么hash值要尽可能地均匀,如果尽可能地均匀,在这里进行取余运算的时候,hash冲突会降低
继续看源码回到putVal函数
if ((p = tab[i = (n - 1) & hash]) == null)
//如果不为空,就插值
tab[i] = newNode(hash, key, value, null);
else{
//产生了Hash冲突
Node<K,V> e; K k;
//判断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);
....(省略部分代码)
//如果一致,将原先的key对应的值做一个替换
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
继续看源码回到putVal函数
假设hash值,key不是一致,另外一种冲突怎么办呢?
//判断p是不是树形节点,至于TreeNode是什么呢?就是红黑树
else if (p instanceof TreeNode)
//如果是树形节点的,就按照红黑树的方式,插入节点
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//如果不是树形节点,以链表的方式,插入节点
//这里有一个binCount计数,计算这个链表的长度
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果这个链表的长度大于8-1
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//接下来我们来看下treeifyBin
treeifyBin(tab, hash);
break;
}
....(省略部分代码)
}
接下来我们来看下treeifyBin()
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//判断是否为空和容量是不是太小
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
//如果是,则要重新调整容量
resize();
//否则
else if ((e = tab[index = (n - 1) & hash]) != null) {
//将单链表转换成红黑树
....(省略部分代码)
}
}
再回到我们的putVal函数
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
//修改的数量
++modCount;
//判断size(实际容量)是否大于阈值,初始值为12
if (++size > threshold)
resize();
afterNodeInsertion(evict);
再次回到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;
if (oldCap > 0) {
//判断是否大于最大值,若已经大于最大值,则将阈值设置为Integer的最大值
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//否则,将阈值扩大一倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
....(省略部分代码)
threshold = newThr;
//生成新得一个容量数组
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//将oldTab的节点插入到newTab中
if (oldTab != null) {
....(省略部分代码)
}
return newTab;
}
至于get和remove方法在这里不过多讲解,相对于set的构建过程比较简单
总结
- HashMap包括了数组,链表,红黑树
- 数组容量为2的幂:
- 提高运算速度
- 增加散列度,降低冲突
- 减少内存碎片
- hash函数:hashcode的高16位和低16位进行异或求模,增加散列度,降低冲突
- 插入冲突:通过单链表解决冲突,如果链表长度超过8,进行链表和红黑树的转换,以提高查询速度
- 扩容的条件:实际节点数大于容量的四分之三,扩容后进行数据排布