HashMap是比较常用的结构,以前也总用但是对HashMap的结构和实现还是挺迷惑的,所以了解下源码,看源码是个痛苦的过程,脑子晕的时候就休息休息~
概述
map常用的方法是put、get,put是将元素存入map的适当位置中,通过key计算hash值,hash值计算完成之后,成为某个节点的一个属性,是不会发生变化的,通过某种计算方式找到key对应桶中的位置。通常key最好使用不可变对象,因为get时,需要通过key来查找该key是否在map中,如果在,在什么位置,对应的value值是什么样的。如果key是可变对象,每次计算的hash值可能会不相同,get时会找不到对应的value,或者取到的值不是put时的value值。
hashMap整体结构
- 结构图:
- 存储结构:数组,可以理解为一个string [] str ,把map数组看成一个桶,数组中的元素是一个键值对节点
- 桶中位置index是指:相同index的节点,存储在桶的同一个位置,
- 桶的大小:整个数组的大小,数组的大小和map的size是有区别的(本文map指HashMap),map的size是指map中包含元素的数量。
key的哈希值相关
- hash值的计算: (h = key.hashCode()) ^ (h >>> 16),h的高16位保持不变,低16位取异或,hash值是Node节点的属性,是保持不变的。
- index的计算:(table.length-1 & hash),不管hash值计算出来的结果多少,决定index值和桶的大小有关系的,桶的大小为2^N,(4-1)->0011,(8-1) -> 0111,(16-1)-> 1111, index的计算只和hash值的某几位有关
- hash&oldCap:扩容时(resize方法)需要给链表中的节点寻找位置的算法。(会将原始链表的长度分割,更加节点分布的更加均匀)
- resize方法将单链表拆分成两个链表时会用的计算。
put方法
- put:hashMap的初始化时,没有指定容量是不分配内存的,当put动作发生时才会为其分配内存
- 思路,
- 计算index的值,确定节点要存储的位置
- 如果桶中的该index位置中不存在节点,则创建,如果存在则找到适合的位置
- 容量检测,如果超过阀值进行扩容
- 源码解读
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; //存放整个map数组,key hash结果的位置就是tab数组中的位置,数组中存放链表或者红黑树的头结点
Node<K,V> p; //当前头结点元素
int n, i;//map的长度 数据的位置 对应头结点p
//当前map为空或者长度为0
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//数组当前位置的没有元素,创建新的元素
if ((p = tab[i = (n - 1) & hash]) == null) //i = (n - 1) & hash 计算index的值
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e;//遍历链表时,表示当前节点
K k; //头结点的key
//头结点的hash值、key 和输入节点的hash key相同,value覆盖
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//当前节点是TreeNode节点
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//死循环,将节点插入到链表中,bigCount用于和是否转变成红黑树的阀值进行比较,
for (int binCount = 0; ; ++binCount) {
//p的下一个节点赋值给e,如果p的下一个节点为空,则创建新的节点,相当于将新的几点插入到链表的末尾
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//链表节点数大与8,转红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//链表中存在hash值、key 和输入节点的hash key相同,则跳出
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
//相当于p=p.next
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
//hashMap这里是覆盖值的
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//当前元素的个数>总容量*负载因子
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
resize方法
- resize:扩容是将map原始容量*2 = 新的map容量
- 思路:
- 将map的容量*2
- 将原始map中节点移动到新的map中
- 源码解读
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length; //老的map的长度
int oldThr = threshold; //老的map的最大容量
int newCap, newThr = 0; //扩容以后map的长度和map的最大容量(负载因子*map容量的)
//老值容量不为0,则进行扩容,扩容二倍
if (oldCap > 0) {
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
}
//老的最大容量值大与0
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);
}
//给扩容后的map设置最大容量和新的map
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//如果老的map不为空,将老map的值存储到新的map对应的位置
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;
}
get方法
- 思路:
- 用(table.length-1 & hash)求index
- 遍历链表或者红黑树寻找key相同的值
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) { //校验以及求桶的位置
if (first.hash == hash && // always check first node 检索是不是第一个元素
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode) //类型是treeNode的查找
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do { //遍历链表
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
红黑树相关问题
这个地方了解的很少,我不敢造次,说一点点我了解的地方
- put方法时涉及到将链表转成红黑树:链表的转成红黑树时,首先需要桶的长度大与64,如果桶的长度小于64,通过resize将桶中的数据相对均匀的分布,resize的过程,可以将链表拆分成两部分的操作。
- 桶中链表大与8转红黑树的原因(抄的):桶中的节点频率遵循泊松分布,桶的长度超过8的概率非常非常小。所以作者应该是根据概率统计而选择了8作为阀值。
- get方法涉及对红黑树中元素的查找
- remove方法涉及对将红黑树转成链表
- TreeNode 红黑树的节点(继承Node节点),Node链表的节点,Node链表转成红黑树时,需要将Node转成TreeNode双向链表,然后由双向链表转成红黑树。
参考:
- resize:https://segmentfault.com/a/1190000015812438?utm_source=tag-newest
- hashMap:https://www.jianshu.com/p/df4a907ef4ef
- 哈希值求法:https://www.jianshu.com/p/b9558ad35f70
- 红黑树:https://www.imooc.com/article/44955