HashMap源码整理
本文基于JDK8分析HashMap源码
概念
根据键值对来访问存储记录的一种数据结构。
基本数据结构
JDK7及以前是数组+链表,JDK8开始使用数组+链表+红黑树
从它的基本数据结构就可以看出,它处理哈希冲突的方法是链地址法。
一些成员变量
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
//map中当前键值对数目
transient int size;
//扩容的阈值,值为当前map中键值对数量 * 负载因子。put方法中,当前键值对数量到达这个值时会将数组扩容
int threshold;
//负载因子,默认值为0.75
final float loadFactor;
//默认初始容量=16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//Node类型的数组
transient Node<K,V>[] table;
}
下面看看这个数组元素的定义:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //hash方法计算出的key的哈希值
final K key;
V value;
Node<K,V> next; //next节点的引用
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
...
}
构造方法
我们常用下面前三个构造方法,可以看到这几个构造方法中都不会先进行初始化数组的操作。初始化操作被延迟到了它的put方法中,如果没有进行初始化就会调用resize方法进行初始化。
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY) //初始容量不会大于最大容量
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
如果传入初始容量这个参数,构造方法中会调用tableSizeFor方法来计算出比初始容量大并且是最小的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;
}
问:为什么HashMap的数组长度总是2的幂次方?
hashMap 的容量是2的n次幂,无论在初始化的时候传入的初始容量是多少,最终都会转化成2的n次幂,这样做的原因是:HashMap计算元素索引的办法为 hash % length == hash & ( length - 1 ) ,当哈希表容量为2的n次方时,length - 1的二进制就是n个1,这样让key的hashcode尽可能多地和1与,尽可能地用到每一位hashcode,可以降低hash冲突
put()
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
下面putVal方法中计算数组索引的方法有两步:
- 通过hash函数计算出key的hashcode
//上面的put方法会通过这个hash方法计算出一个哈希值并传给putVal方法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
问:这个哈希值为高16位和低16位异或的结果,那么为什么要这么做呢?
主要是为了减少哈希冲突,让元素尽可能离散地分配到数组中。
- 通过与运算计算出索引
(n - 1) & hash //n为数组长度,hash为上面key计算出的hashcode
- 优点:使用与运算效率较取模高很多;同时还能减少哈希碰撞,使计算出的索引更为离散。
putVal()
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//1.数组为null或长度为0,即第一次放入元素
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length; //resize方法会初始化数组或进行扩容,这里进行初始化
//2.如果数组当前位置没有元素,就直接在此处放入一个新创建的Node
if ((p = tab[i = (n - 1) & hash]) == null) //当前索引元素为空
tab[i] = newNode(hash, key, value, null);
else { //当前位置已经有元素
Node<K,V> e; K k;
//3.待存元素的key和当前位置的首元素(table[i])的key相等,直接覆盖value
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode) //4.table[i]是否为红黑树,是则插入红黑树
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//5.遍历链表,如果遍历到了表尾就直接将元素插入表尾,并判断是否需要将链表转换为红黑树;遍历过程中,如果有节点的key和待存元素的key相等就直接覆盖value
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) { //遍历到了表尾,直接在table[i]链表末尾插入一个新的节点
p.next = newNode(hash, key, value, null);
//如果链表元素>=8,就将它转换为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//链表当前节点的key和待存元素的key相等就直接覆盖value
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;
//6.如果插入元素后,数组已使用元素大于阈值,就调用resize方法将数组扩容为2倍,同时将原数组中所有元素复制到新数组中
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
步骤小结
-
判断数组是否为null或长度为0,是就通过resize方法将table数组初始化
这里再说一下resize方法的作用:对数组进行初始化或扩容操作(扩容后数组容量不超过最大容量),扩容后会将原数组中的元素赋给新的数组。
-
计算key的hashcode和index,如果当前位置没有元素就直接插入。
-
待存元素的key和当前位置的首元素(table[i])的key相等,直接覆盖value
-
如果首元素已经存储了元素并且是TreeNode的实例,那么这是一个红黑树,将其插入红黑树中。
-
遍历当前索引的链表,如果到了链表表尾,则插入元素到表尾。插入后进行判断,如果链表元素>=8,就将它转换为红黑树;
遍历过程中,如果链表当前节点的key和待存元素的key相等就直接覆盖value。
-
检查哈希桶是否达到阈值,如果达到了就调用resize方法将数组扩容为2倍的长度。
get()
下面接着分析HashMap的get方法:
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
首先通过hash方法计算出key的哈希值,再通过getNode方法获取表中元素
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) { //判断数组是否初始化过(put方法中会将数组初始化)、长度table数组长度是否>0 和 当前索引的首元素是否为null
//先判断首元素的key是否和待取元素的key相等,是则直接返回首元素,get方法最终返回它的value
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//如果此位置是红黑树就从红黑树中寻找元素;否则遍历数组此位置的链表直到表尾,找到直接返回该节点,否则返回null,最终get方法返回对应的value或null。
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;
}
remove()
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
//调用removeNode移除查找到的元素,移除成功返回该节点,否则返回null
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);
}
}
//上面寻找Node的步骤和get方法很类似,下面if语句先判断上面是否找到要删除的节点
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode) //找到的节点是红黑树就调用removeTreeNode方法移除节点
((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;
}