HashMap
version:1.8
HashMap基于哈希算法实现对存储的键值对的快速查询,其在多线程下使用不安全。
本文红黑树相关的内容不多做介绍。
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
每一条键值对使用一个Node结点存储,使用Node数组存储所有的键值对。
transient Node<K,V>[] table;
static class Node<K,V> implements Map.Entry<K,V>{
final int hash;
final K key;
V value;
Node<K,V> next;
…………
}
get
get源码比较简单,因此先看get源码。
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
先看看hash算法 ,其首先采用key自身的hashCode()方法获得哈希值,然后将其右移16位与自身进行异或从而获得实际使用的哈希值,对于null返回0。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
进一步看getNode源码:
首先判断table是否为空,长度是否大于0,hash值对应位置是否为空,若为空,返回null。
此处需注意,hash值对应的位置需要将hash值与table的长度减一进行 “与” 操作(此处结果等价于求模table的长度),避免hash值大于数组长度。
由于table的长度为2的n次方(见resize),简单举例,如8,减1后二进制为0111,进行“与”操作相当于屏蔽掉7以上的位数,相当于对8求模。
之后判断第一个找到的结点是否确实是要寻找的结点,首先判断hash值,进一步判断key是否相等,使用==判断(key为基本类型或null)与equals方法判断(key不为null)。
若不是,发生了哈希冲突,HashMap使用链地址法解决哈希冲突,正如前面看到的Node结点的字段Node<K,V> next,通过遍历链表寻找我们想要的结点。
但遍历链表导致寻找效率降低,为解决此问题,当链表长度过长,JDK选择将链表转化为红黑树,提高寻找效率,因此首先需判断结点是否为树节点,若是树节点,调用getTreeNode寻找想要的结点。
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab;
Node<K,V> first, e;
int n; //tab.length
K k;
if ((tab = table) != null && (n = tab.length) > 0 && //table不为空且长度大于0
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && ((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;
}
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V>
put
接下来看下put源码:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
看过get,理解put就很简单了。
如果未发生哈希冲突,直接新建结点即可,之后需判断是否需要扩容。
发生哈希冲突,首先判断当前结点是否为树节点,树节点调用putTreeVal插入结点,如果key已存在,返回对应的结点。否则遍历链表,如果key存在,跳出,否则在链表尾部新建结点,此时判断链表长度是否过长,过长尝试将链表转化为红黑树(注意此时还不一定转换)。
之后若key已存在,更新对应结点的value。
源码中存在方法如afterNodeAccess(e);,但其是空实现,是为子类扩展做准备。
static final int TREEIFY_THRESHOLD = 8;
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)))) //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) // -1 for 1st //链表过长
treeifyBin(tab, hash); //尝试转换为红黑树
break;
}
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//key存在,更新value
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;
}
//空实现,为子类扩展做准备
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }
进一步查看treeifyBin源码,如果table长度小于64,此时扩容而非将链表转化为红黑树。
将链表转换为红黑树有两个条件:链表长度大于等于8,table长度大于等于64。
static final int MIN_TREEIFY_CAPACITY = 64;
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);
}
}
resize
从前文我们可以看到一个出现了很多次的方法,resize,接下来看下它的源码。
源码分为两大步:
首先确定新的threshold,table长度,除了一些异常情况的处理,就是将原来的大小乘以二,加上初始容量的处理(必为2的幂,tableSizeFor()),故table的长度必为2的幂。
接下来就是对存储的键值对重新哈希化。
同前文,分为三种情况。
(1)未发生哈希冲突直接计算新的位置即可。
(2)发生哈希冲突,通过链表存储,可将链表拆分为两条。
- 新的table长度为原来的两倍,对其求模相当于与运算多了一位。
- 若哈希值二进制形式在该位为0,位置不变;为1,在新的table的位置为(原位置+原table长度)。
(3)发生哈希冲突,通过红黑树存储。TreeNode<K,V> extends LinkedHashMap.Entry<K,V>,树节点其实也保存有链表结构,同链表处理将其划分成两条后,根据其长度判断将其改为链表还是重新组织成红黑树。
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
//新的threshold,table长度的确定
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;
}
情况(3)部分代码:
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);
}
}
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;
}