此文章基于Java1.8,主要从结构、hash过程、put数据、get数据以及resize几个方面来介绍HashMap。
结构
主要由数组+链表+红黑树组成,关于链表和红黑树的具体相关操作请另行查看哦!
主要参数:
transient Node<K,V>[] table;//数组结构
transient int size;//HashMap数据大小
int threshold;//未初始化时表示初始化大小,初始化完成后表示数组大小*loadFactor
final float loadFactor;//加载因子
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
//构造函数、hashCode、equals、set、get等。。。
}
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
//构造函数、关于树的各种操作、树转链表、链表转树等。。。
}
Hash
- 计算key的哈希值
hash = (h = key.hashCode()) ^ (h >>> 16)
- 选择下标位置
(n - 1) & hash
,n为数组长度
h>>>16
是为了扰动,把高位的特征和低位的特征组合起来,降低哈希冲突的概率,尽量做到任何一位的变化都能对最终得到的结果产生影响。
x % 2n = x & (2n - 1):位运算的效率更高
2n 表示2的n次方,也就是说,一个数对2n 取模 == 一个数和(2n – 1)做按位与运算 。
假设n为3,则23 = 8,表示成2进制就是1000。23 -1 = 7 ,即0111。
此时X & (23 – 1) 就相当于取X的2进制的最后三位数。
从2进制角度来看,X / 8相当于 X >> 3,即把X右移3位,此时得到了X / 8的商,而被移掉的部分(后三位),则是X % 8,也就是余数。
put数据
计算数组下标位置,找到后,如果该位置没有元素直接存入,否则判断key是否相同,相同覆盖,反之插链表或红黑树,最后判断数组长度是否超过threshold,超过则进行扩容。
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;//tab初始化
if ((p = tab[i = (n - 1) & hash]) == null)//寻找下标位置为空
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))//下标位置即为要找的key
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);//插入尾部
if (binCount >= TREEIFY_THRESHOLD - 1) // 判断是否需要转红黑树
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
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)//数组是否需要扩容
resize();
afterNodeInsertion(evict);
return null;
}
get数据
计算出hash值,然后去数组查询,先查看是否是下标位置节点,不是则判断下标Node是红黑树就去红黑树查询,是链表就遍历链表查询。
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)//树查找
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;
}
reszie
关于扩容时,当前Node节点数据的迁移,若当前下标位置为i,则此节点上的数据迁移后的下标位置为i
或i+oldCap
。
下标位置:hash&(len-1) = hash & (2*oldCap - 1) = ((hash & oldCap) + (hash&(oldCap-1))) = (hash & oldCap) + i
当hash&oldCap
为0时,新表下标为i
,否则新表下标为i+oldCap
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) {//tab不为空
if (oldCap >= MAXIMUM_CAPACITY) {//tab容量不能再大了,返回不再进行扩容
threshold = Integer.MAX_VALUE;
return oldTab;
}
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;//16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//16*0.75
}
if (newThr == 0) {//容量是设定的,判断thr是否合理并赋值
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;//newCap*loadFactor
@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) {//某Node不为空
oldTab[j] = null;//旧表赋空
if (e.next == null)//只有一个Node,直接赋值新tab
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) {//与的结果0为一组,1为一组
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) {//0的结果放newTab当前位置
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {//1结果放newTab j+oldCap 位置
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
众所周知,这不是一个线程安全的map,并发环境下建议使用ConcurrentHashMap,下一篇即将介绍呢!
文章是自己理解总结,不一定完全正确,如有问题,请指出,我们一起学习。
若有部分内容或图片侵权,请联系删除!
参考内容:
全网把Map中的hash()分析的最透彻的文章,别无二家。
其中有张图是从别人的ppt上拷贝的,不确定来源。