HashMap源码分析
大约 4 分钟java基础集合框架
概述
HashMap实现了Map接口并提供了Map接口的所有功能,以key,value形式保存数据,支持空键和空值,HashMap不保证数据的顺序性,并且HashMap不是线程安全的。HashSet底层基于HashMap实现,key为HashSet的值,value为空值。
结构
HashMap采用数组+链表存储数据,示意图如下所示:
执行过程如下:
源码分析
相关源码都是基于JDK8进行分析。
关键属性
// HashMap默认大小
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 默认的负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 当链表长度大于8时,会自动将链表转为红黑树
static final int TREEIFY_THRESHOLD = 8;
put方法源码解析:
/**
* Implements Map.put and related methods
*
* @param key的hash值
* @param key值
* @param value值
* @param onlyIfAbsent如果是true,则不修改已存在的value值
* @param evict if false, the table is in creation mode.
* @return 返回被修改的value,或者返回null。
*/
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)
//如果是第一次调用,则会调用resize 初始化table 以及threshold
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
//如果对应的索引没有Node,则新建Node放到table里面。
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))))
//如果hash值与已存在的hash相等,并且key相等,则准备更新对应Node的value
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//如果hash值一致,但是key不一致,那么将新的key-value添加到已有的Node的最后面
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // 当某个节点的链表长度大于8,则扩大table 数组的长度或者将当前节点链表变成树节点链表
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)
//hash值和key值相等的情况下,更新value值
e.value = value;
//留给LinkedHashMap实现
afterNodeAccess(e);
//返回旧的value
return oldValue;
}
}
//修改次数加1
++modCount;
//判断table的容量是否需要扩展
if (++size > threshold)
resize();
//留给LinkedHashMap扩展
afterNodeInsertion(evict);
return null;
}
treeifyBin方法解析:
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//当数组长度小于64时,扩大数组
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);
}
}
扩容实现:
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
// 当前数组大小
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 当前的阈值
int oldThr = threshold;
int newCap, newThr = 0;
// 如果table数组已有值,则将其容量(size)和阈值(threshold)扩大两倍
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;
//将以前table中的值copy到新的table中去
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;
}
getNode实现:
/**
* Implements Map.get and related methods
*
* @param key 的hash值
* @param key的值
* @return 返回由key和hash定位的Node,或者null,查询相对来说比较简单,按照put的逻辑进行查询。
*/
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) {
// 如果索引到的第一个Node,key 和 hash值都和传递进来的参数相等,则返回该Node
if (first.hash == hash &&
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//如果索引到的第一个Node 不符合要求,循环变量它的下一个节点。
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;
}
总结
- HashMap不是线程安全的,如果需要线程安全,可使用
Collections.synchronizedMap()
和ConcurrentHashMap
- 当HashMap的size大于capacity * loadFactor 时,会自动进行扩容,每次扩容后,容量为原来的 2 倍,并进行数据迁移,在实例化 HashMap 时可以为其设置一个合适的初始值。设置初始值,可以 HashMap 在初始化时不必开辟过多的内存,也可以避免不断的进行扩容,扩容是一个特写消耗性能的操作。
- JDK1.8引入红黑树大程度优化了HashMap的性能。