HashMap 源码
数据结构
HashMap 是一个存储键值对的数据结构,主体是由一个数组构成,数组的大小有限,因此当 key 的 hash 相等时通过拉链法解决冲突,也就是在之前的 key 后面连接一个节点组成链表,当链表长度过长时该链表可能会变为红黑树提高查询效率。
构造函数
第一个构造函数包含两个参数, initialCapacity
表示初始容量,用于指导数组的初始容量; loadFactor
表示负载因子,用于判断数组在何时需要扩容,越小时元素碰撞概率越小,数组占用空间也越大。
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);
}
其中还对 threshold
进行了赋值,它表示数组中元素超过多少时需要扩容。
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;
}
上面的位运算含义为将最高位的1后面的位全部变成 1,例如:tableSizeFor(7) == 8,tableSizeFor(9) == 16 。
查找
get
方法通过 (n - 1) & hash
取 hash(n - 1 最大程度保存了 hash 的差异)。 n
表示数组长度(永远为 2 的倍数);hash
是表示 key 的 hashcode,具体是通过 hash 方法, ^ (h >>> 16)
是因为数组长度通常很小,防止高位的 hash 差异被忽略导致低位 hash 相同概率变大,而 key 为空时返回 0 说明 HashMap 的键值对 key 是可以为空的。另外判断 key 相等的条件是 hashCode()
、==
和 equals()
,因此需要重写这两个方法。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
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)
// 是红黑树,调用 getTreeNode 查找
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;
}
插入
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)
// 没有 hash 碰撞,直接放入数组
tab[i] = newNode(hash, key, value, null);
else {
// 有 hash 碰撞,e 用于保存 key 相同的原键值对
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
// 链表长度大于等于 8,可能需要转为红黑树
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
// 找到了相同的 key
break;
p = e;
}
}
if (e != null) {
// 存在相同的 key,替换键值对的 value,返回 oldValue
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 新键值对放入了数组中,当数组中超过扩容阈值,扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
初始化和扩容
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;
}
else if (oldThr > 0)
// 通过 HashMap(int initialCapacity, float loadFactor) 或
// HashMap(int initialCapacity) 创建,扩容阈值已经初始化
newCap = oldThr;
else {
// 通过 HashMap() 创建,使用默认容量和扩容阈值
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
// 第 16 行左移变成 0 或者是第 19 行没初始化扩容阈值
float ft = (float)newCap * loadFactor;
// 新数组容量小于 MAXIMUM_CAPACITY 并且 newCap * loadFactor 小于 MAXIMUM_CAPACITY
// 时取 ft,否则取 Integer.MAX_VALUE(可能是 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
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)
// 只有一个节点,重新 hash
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 红黑树
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else {
// 链表,重新 hash 到 low Node 和 high Node
// 下面以初始化长度为 4,table[0] key 为 0,table[0].next key 为 4 举例说明
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) {
// hash 没变,放到 low Node 组成链表
// 例如:table[0] 的 0 还是在 table[0]
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
// hash 与原数组 hash 不同
// 例如:table[0].next 的 4 需要分配到 table[0 + 4]
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
// 指向新 low 链表
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
// 指向新 head 链表
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
删除
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;
}