1、底层结构
JDK1.8之前的结构
在JDK1.7之前,HashMap采用的是数组+链表的结构,其结构图如下:

数组的每一个元素都是一个单链表的头节点,链表是用来解决冲突的,如果不同的key映射到了数组的同一位置处,就将其放入单链表中。
JDK1.8的结构
JDK1.8之前的HashMap都采用上图的结构,都是基于一个数组和多个单链表,hash值冲突的时候,就将对应节点以链表形式存储。如果在一个链表中查找一个节点时,将会花费O(n)的查找时间,会有很大的性能损失。到了JDK1.8,当同一个Hash值的节点数不小于8时,不再采用单链表形式存储,而是采用红黑树,如下图所示:

2、基本操作
添加一个元素put(K k,V v)
public V put(K key, V value) {
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;
//如果哈希表为空或长度为0,调用resize()方法创建哈希表
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//如果哈希表中K对应的桶为空,那么该K,V对将成为该桶的头节点
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//该桶处已有节点,即发生了哈希冲突
else {
Node<K,V> e; K k;
//如果添加的值与头节点相同,将e指向p
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果与头节点不同,并且该桶目前已经是红黑树状态,调用putTreeVal()方法
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//桶中仍是链表阶段
else {
//遍历,要比较是否与已有节点相同
for (int binCount = 0; ; ++binCount) {
//将e指向下一个节点,如果是null,说明链表中没有相同节点,添加到链表尾部即可
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果此时链表个数达到了8,那么需要将该桶处链表转换成红黑树,treeifyBin()方法将hash处的桶转成红黑树
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
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//子类实现
afterNodeAccess(e);
return oldValue;
}
}
//是一个全新节点,那么size需要+1
++modCount;
//如果超过了阈值,那么需要resize()扩大容量
if (++size > threshold)
resize();
//子类实现
afterNodeInsertion(evict);
return null;
}
从上面代码可以看到putVal()方法的流程:
1. 判断哈希表是否为空,如果为空,调用resize()方法进行创建哈希表
2. 根据hash值得到哈希表中桶的头节点,如果为null,说明是第一个节点,直接调用newNode()方法添加节点即可
3. 如果发生了哈希冲突,那么首先会得到头节点,比较是否相同,如果相同,则进行节点值的替换返回
4. 如果头节点不相同,但是头节点已经是TreeNode了,说明该桶处已经是红黑树了,那么调用putTreeVal()方法将该结点加入到红黑树中
5. 如果头节点不是TreeNode,说明仍然是链表阶段,那么就需要从头开始遍历,一旦找到了相同的节点就跳出循环或者直到了链表尾部,那么将该节点插入到链表尾部
6. 如果插入到链表尾部后,链表个数达到了阈值8,那么将会将该链表转换成红黑树,调用treeifyBin()方法
7. 如果是新加一个数据,那么将size+1,此时如果size超过了阈值,那么需要调用resize()方法进行扩容
get(K k)操作
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//根据键的hash值和键得到对应节点
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//可以从桶中得到对应hash值的第一个节点
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) {
//如果首节点是红黑树节点,调用getTreeNode()方法
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;
}
从上面代码可以看到getNode()方法中有多种情况:
1. 表为空或表的长度为0或表中不存在key对应的hash值桶,那么返回null
2. 如果表中有key对应hash值的桶,得到首节点,如果首节点匹配,那么直接返回;
3. 如果首节点不匹配,并且没有后续节点,那么返回null
4. 如果首节点有后续节点并且首节点是TreeNode,调用getTreeNode方法寻找节点
5. 如果首节点有后续节点并且是链表结构,那么从前往后遍历,一旦找到则返回节点,否则返回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;
//旧表存在
if (oldCap > 0) {
//旧表已经达到了最大容量,不能再大,直接返回旧表
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//否则,新容量为旧容量2倍,新阈值为旧阈值2倍
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;
//初始化时没有指定阈值和容量,使用默认的容量16和阈值16*0.75=12
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;
//如果属于容量扩展,rehash操作
if (oldTab != null) {
//遍历旧表
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//如果该桶处存在数据
if ((e = oldTab[j]) != null) {
//将旧表数据置为null,帮助gc
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
//下面这段暂时没有太明白,通过e.hash & oldCap将链表分为两队,参考知乎上的一段解释
/**
* 把链表上的键值对按hash值分成lo和hi两串,lo串的新索引位置与原先相同[原先位
* j],hi串的新索引位置为[原先位置j+oldCap];
* 链表的键值对加入lo还是hi串取决于 判断条件if ((e.hash & oldCap) == 0),因为* capacity是2的幂,所以oldCap为10...0的二进制形式,若判断条件为真,意味着
* oldCap为1的那位对应的hash位为0,对新索引的计算没有影响(新索引
* =hash&(newCap-*1),newCap=oldCap<<2);若判断条件为假,则 oldCap为1的那位* 对应的hash位为1,
* 即新索引=hash&( newCap-1 )= hash&( (oldCap<<2) - 1),相当于多了10...0,
* 即 oldCap
* 例子:
* 旧容量=16,二进制10000;新容量=32,二进制100000
* 旧索引的计算:
* hash = xxxx xxxx xxxy xxxx
* 旧容量-1 1111
* &运算 xxxx
* 新索引的计算:
* hash = xxxx xxxx xxxy xxxx
* 新容量-1 1 1111
* &运算 y xxxx
* 新索引 = 旧索引 + y0000,若判断条件为真,则y=0(lo串索引不变),否则y=1(hi串
* 索引=旧索引+旧容量10000)
*/
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;
}
从上面可以看到,resize()首先获取新容量以及新阈值,然后根据新容量创建新表。如果是扩容操作,则需要进行rehash操作,通过e.hash&oldCap将链表分为两列,更好地均匀分布在新表中。
hash(Object key)
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
从上面的代码可以看到key的hash值的计算方法。key的hash值高16位不变,低16位与高16位异或作为key的最终hash值。(h >>> 16,表示无符号右移16位,高位补0,任何数跟0异或都是其本身,因此key的hash值高16位不变。)
为什么要这么干呢?
这个与HashMap中table下标的计算有关。
n = table.length;
index = (n-1) & hash;
因为,table的长度都是2的幂,因此index仅与hash值的低n位有关,hash值的高位都被与操作置为0了。
假设table.length=2^4=16。

由上图可以看到,只有hash值的低4位参与了运算。
这样做很容易产生碰撞。设计者权衡了speed, utility, and quality,将高16位与低16位异或来减少这种影响。设计者考虑到现在的hashCode分布的已经很不错了,而且当发生较大碰撞时也用树形存储降低了冲突。仅仅异或一下,既减少了系统的开销,也不会造成的因为高位没有参与下标的计算(table长度比较小时),从而引起的碰撞。
本文详细解析了HashMap在JDK1.8前后的结构变化,包括数组+链表到数组+链表/红黑树的转变,以及基本操作如put、get、resize的实现原理。
701

被折叠的 条评论
为什么被折叠?



