HashMap
HashMap是一个k-v的查找表
class HashMap<>{
//表,在第一次使用时初始化,并根据需要调整大小。分配时,长度总是2的幂(在某些操作中,我们还允许长度为零,以允许当前不需要的引导机制)。
transient Node<K,V>[] table;
//entry的缓存
transient Set<Map.Entry<K,V>> entrySet;
//大小
transient int size;
//结构改变次数,用于快速失败
transient int modCount;
//负载因子
int threshold;
}
HashMap使用key的hash确定存放在数组中的位置,使用拉链法处理hash冲突,拉链使用链表(len<=8)或红黑树(>8)
putVal函数
如下是put函数的实现
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;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
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))))
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) // -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;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
可以看到无论如何都会进行第一个操作,即是检查table有没有初始化(tab==null || tab.length==0
),如果没有初始化则将进行resize()
初始化
后续的代码看起来比较长,但其实可以分为两种情况进行讨论
- key存在映射值
- key不存在映射值
若存在映射值(通过equals),则说明此次仅有可能覆盖旧值,否则说明此次必然会造成一次结构的改变
因为存储结构是数组,因此需要使用hash计算对应数组的位置
n=tab.length
index=(n - 1) & hash
这就是为什么需要保证tab.length是2的幂次.(n-1)&hash==hash%n
在netty中的LoopChooser也有一个实现是使用这种方式的.
如果index上是null,则说明没有equals(k).
而index是可能存在冲突的,即index上有值,此时就需要查找RBTree
和Linked
中的node比是否存在equals(k)
查找后,根据e
的值判断是否存在old.node
为什么说是有可能覆盖旧值,这里使用e作为是否存在旧值existing mapping for key
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
这里根据onlyIfAbsent
和oldValue
决定是否将新值替换旧值,然后返回old.value
.
而对于没有找到旧值存在的情况,则说明发生了结构修改
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);//对于HashMap是空实现
除此之外,存在一个特殊的结构性修改
即拉链新增了一个node,这种情况可能导致链表模型的改变
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
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;
}
TREEIFY_THRESHOLD
是final的默认值是8,并且没有提供修改的方式.因此这里的treeifyBin
临界点为8
然而,即使调用了这个函数,也不一定进行树化
,还有另外一个条件tab.length>=MIN_TREEIFY_CAPACITY
,这个MIN_TREEIFY_CAPACITY
默认值是64,仍然是使用的final值.
也就是说**linked.size>=8 && tab.length>=64**,才会进行树化
的操作,这和网上大部分的说明只要linked.size>=8
的条件完全不一样.
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) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
回到putVal
函数,最后则是计算增加后的size
是否到达了resize的阈值.如果达到的话,则进行resize
getNode函数
下面是get函数
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
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;
}
相对于put函数,get显得更加简单了不少
- 计算index
- 比对index的第一个hash值和equals,如果相同则直接返回
- 在
RBTree
或Linked
中查找
这里要说明一下为什么Node中会存储一个hash,其实这里有两个作用
- 避免多次计算同一个hash
- 对于可变的key,如果key改变的内容不会导致equals失败,那么HashMap还是能够正常工作的
另外还有一个使用上的注意点
不要使用如下的代码来进行检查是否存在k-v映射
map.get(k)==null;
使用containsKey
函数
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
因为HashMap
是可以存储null值的.但即使是null值,也是对应了一个Node对象的
remove函数
下面是remove
方法
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
套路和put函数差不多
- key存在映射值
- key不存在映射值
不存在映射值没什么好说的,直接返回null.
如果存在映射值,根据key
查找映射的Node
查找的过程分为3种
- Node直接存储在tab上
- Node存储在
RBTree
- Node存储在
Linked
找到了符合映射的Node
后,按照matchValue
进行操作
- matchValue==false
- matchValue==true
如果不需要匹配Value,则进行删除,自然删除的过程也分为3种,这里有个小技巧
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
删除链表
对于链表的非首非null节点,找到前置节点,pre.next=pre.next.next即可
remove如果操作到了节点自然也会产生结构性的变化
afterNodeRemoval
仍然是空实现
这里有个非常神奇的操作,remove使得数据量下降时,HashMap是没有进行resize()
操作的.
搜索一下resize()的引用,说明只有"添加"的时候才会进行resize
(treeifyBin
函数就是试图树化
的操作)
![1558452161710](C:\work\document\jdk源码\resize的引用
但是有可能会进行链化
操作,即untreeify
函数.
下面是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;
}
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;
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;
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;
}
前面一段是在计算newCap的大小,同样分为几种情况讨论
- map尚未初始化
- 当前map的容量已经达到了上限
- map容量尚未到达上限
在map已经初始化,并且尚未达到上限的情况下,newCap总是oldCap的2倍,这也是为什么最大容量的值为1<<30
的原因:
int的最大值为1<<31-1,如果超过这个值则会变成负数.导致各种判断都存在问题,因此
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
不进行扩容,并将threshold
设置为Integer.MAX_VALUE.
如果目前符合限制,则会尝试计算下次resize
的阈值.即newThr=oldThr<<1
若map尚未初始化,并且指定了threshold
其实表明了期望初始化后的容量值
if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
否则初始化将会使用默认值DEFAULT_INITIAL_CAPACITY
16,而resize
阈值会被设置为(int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
DEFAULT_LOAD_FACTOR
为0.75
最后会进行一次托底操作
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
其实针对的情况为map尚未初始化,并且指定了threshold
至此,已经得出newCap的值,随后直接创建一个newCap的数组替换table
然后进行数据迁移的操作,同样可以分为几种情况讨论
- 当前index无值
- 当前index的值不存在链路
- 当前index为
RBTree
- 当前index为
linked
1.2情况无需讨论,先看一下简单的情况4
如果当前节点存在拉链
,说明拉链上的节点(n-1)&hash
值都是相同的
而由于n是2的幂次,因此,这里又会分为两种情况
- n的二进制位中的1的位置对于hash值是1
- n的二进制位中的1的位置对于hash值是0
由于newCap=oldCap<<1;因此若为情况2,(newCap-1)&hash==(old-1)&hash
的值相同,该节点仍然处于当前位置.而对于情况1,(newCap-1)&hash=((old-1)&hash)|old
.又因为old是2的幂次,因此((old-1)&hash)|old==((old-1)&hash)+old
这种情况可能会生成2个链表,这里使用的是尾插法
情况3
这里要说明一下TreeNode
是继承于Node
的,因此链表结构是仍然存在的.
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
for (TreeNode<K,V> e = b, next; e != null; e = next) {
next = (TreeNode<K,V>)e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
if (loHead != null) {
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {
tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}
这里用了一种 比较巧妙的方式:
- 整理链表状态
- 如果链表的长度<=
UNTREEIFY_THRESHOLD
,则调用untreeify
将RBTree
退化为Linked
- 否则使用链表结构重新
treeify
这里还用了一个技巧,如果整理loHead
的时候,发现没有hiHead
,说明树的结构没有改变,反之也相同.
UNTREEIFY_THRESHOLD
这个值是final的6
untreeify
即链化
操作,仅会在split
和removeTreeNode
中进行操作,而split
仅在此调用
关于TreeNode
继承了Node
结构,还有一个经常使用的地方
containsValue
函数
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}
另外还有几个优化的点
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;//缓存
}
return ks;
}
public Collection<V> values() {
Collection<V> vs = values;
if (vs == null) {
vs = new Values();
values = vs;//缓存
}
return vs;
}
//这个函数在使用initialCapacity的构造器和putMapEntries中使用,目的是为了计算出大于cap的最小2幂次数
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;//计算掩码
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
这里之所以可以使用缓存进行优化,是因为KeySet和Values实际上访问的都是实际存储数据的table
computeIfAbsent
不存在时计算.//计算时不会使用oldValue
computeIfPresent
存在时计算.//计算时会使用oldValue
需要注意的是如果计算的值为null,是不会添加到map中的,
compute
在计算新值后,如果为null,会移除掉原有的Node
,即ContainsKey(k)==false
computeIfAbsent
和compute
都有可能引发结构的变化
merge
如果指定的键尚未与值关联或与null关联,则将其与给定的非空值关联。
最后,关于RBTree
部分
因为是一个有序的树结构,因此需要比较
- 如果实现了Compareable接口,则可以比较,(即使是Compareable接口,如果比较后相同,仍然会继续),这里使用了
comparableClassFor
函数 - 否则使用
getClass
进行比较 - getClass相同的情况下,使用
identityHashCode
的值进行比较
//如果它的形式为“class C implements omparable <C>”,则返回x的Class,否则返回null。
static Class<?> comparableClassFor(Object x) {
if (x instanceof Comparable) {
Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
if ((c = x.getClass()) == String.class) // bypass checks
return c;
if ((ts = c.getGenericInterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
if (((t = ts[i]) instanceof ParameterizedType) &&
((p = (ParameterizedType)t).getRawType() ==
Comparable.class) &&
(as = p.getActualTypeArguments()) != null &&
as.length == 1 && as[0] == c) // type arg is c
return c;
}
}
}
return null;
}
static int compareComparables(Class<?> kc, Object k, Object x) {
return (x == null || x.getClass() != kc ? 0 :
((Comparable)k).compareTo(x));
}