HashMap是常用的一个Map容器,同时也是面试时考察Java基础的一个关键点。为了更好的使用抑或面试我们都应该去了解下其实现原理,网上介绍其源码的文章有很多,建议大家还是自己跟进源码学习下,通过本文大家能了解到HashMap的如下内容:
- 数据结构
- 构造方法
- 添加数据逻辑
- 移除数据逻辑
- 获取数据逻辑
- 扩容逻辑
在本篇文章中的源码来自于JDK1.8,更早的版本实现会有区别。
1、数据结构
HashMap的数据结构由数据、链表和红黑树组成,链表和红黑树会根据节点的数量进行转换,其结构入下图所示:
知道了数据结构后,我们对其进行元素的添加、删除及获取操作,就是围绕着相应的数据结构来进行了,其具体逻辑我们会在后面的内容中详细介绍,这里我们介绍下其成员属性
size用来记录容器中的元素数量modCount用来记录对元素的操作次数threshold当元素数量超过该值时会进行扩容loadFactory负载因子 当元素数量百分比超过该值时会进行扩容
2、构造函数
在HashMap中提供了多种构造函数,我们可以指定容器的初始化大小和负载因子,也可以传递一个Map进行创建。
2.1、指定初始化大小和负载因子
public HashMap(int initialCapacity, float loadFactor) {
// 初始化大小小于0会抛出异常
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;
// 设置threshold值
this.threshold = tableSizeFor(initialCapacity);
}
这里需要注意的一点时,threshold变量记录的并不是我们传递过来的值,而是一个经过tableSizeFor方法处理后的值,经过这个方法处理后会返回大于传递的值且是2的n次方的最小的数字,例如我们传递的值为6,实际设置到threshold的值为8。
2.2 指定初始化大小
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
当我们只指定初始化大小时,也会调用2.1中的构造方法,此时传递的负载因子为默认值0.75。
2.3 空参构造
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
当我们调用空参构造时,HashMap没有处理逻辑,仅仅给loadFactory变量设置了一个默认值0.75,那么是在什么时候为threshold变量设置的值呢?我们留到下面进行介绍。
2.4、使用Map
public HashMap(Map<? extends K, ? extends V> m) {
// 设置负载因子为默认值
this.loadFactor = DEFAULT_LOAD_FACTOR;
// 插入元素
putMapEntries(m, false);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
// 传递的map不为空
if (s > 0) {
// 数组尚未初始化 计算并设置threshold
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
// 传递的map元素数量大于需要扩容的值 调用resize方法
else if (s > threshold)
resize();
// 遍历元素添加到hashMap中
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
在上面的源码中会调用resize和putVal两个方法,这两个方法的具体逻辑我们也在后面的内容中进行说明。
3、添加元素
创建好了HashMap对象后我们就可以向其中添加元素了,其添加元素的源码如下:
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;
// 如果还没进行初始化,会调用resize方法进行初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 如果数组对应的位置为空 直接创建一个Node对象放在该位置
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 判断数组上对应的数据的key是否和添加的key一致
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) {
// 链表中不存在对应的key在链表的尾部插入元素
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 如果链表的长度大于等于8需要调用treeifyBin方法
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 链表中存在对应的key
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// e不为null代表key之前已经存在
if (e != null) { // existing mapping for key
// 获取之前的值
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
// 修改value为新值
e.value = value;
afterNodeAccess(e);
// 返回原值
return oldValue;
}
}
// 如果是新增元素 将modCount加1
++modCount;
// 判断元素数量是否超过了threshold 超过了调用resize进行扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
添加元素的方法中处理内容主要如下:
1、数组未初始化会先进行初始化
2、通过hash定位到元素在数组上的位置,该位置未空,直接创建Node对象放到该位置,否则会遍历链表将数据插入链表尾部。
3、链表尾部添加元素后判断链表长度是否大于等于8,满足的话会调用treeifyBin方法,进行扩容或者转为红黑树
4、是新增元素记录modCount的值并判断节点数量是否超过了threshold,超过了需要进行扩容
5、返回原值,之前不存在key返回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对象
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);
}
}
通过上面的源码能够看出,链表转换为红黑树除了判断链表长度外,还会判断数组长度是否大于64,满足的情况下才会转换为红黑树,否则会进行一次扩容操作。
在上面的源码中,我们发现在初始化和扩容时都会调用到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;
}
// 可以扩容的话会将数组长度扩大为原来的2倍
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;
// 未初始化且调用的空参构造 初始大小为默认值16
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
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;
}
在这段代码中主要处理了如下三种情况的逻辑:
- 初始化且创建对象时调用的为空参构造 此时数组长度为默认值16
- 初始化且创建对象时指定了大小 此时数组长度为
tableSizeFor计算出的值 - 扩容 长度允许的情况下会扩大为原来的2倍,否则取最大值 然后将原数据复制到新的数组中
4、获取元素
HashMap获取元素的源码如下:
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;
}
获取元素的逻辑很简单,如下:
- 通过hash计算出在数组的位置
- 数组对应的位置有数据且key为传递过来的key 直接返回
- 数据对应的数据为链表或者红黑树则进行遍历
- 未找到返回null
5、移除元素
移除元素的源码如下:
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自增
++modCount;
// 元素数量减一
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
至此我们今天的文章就结束了,在本篇文章中我们介绍了下HashMap的数据结构及添加、获取、新增元素的逻辑。
HashMap是非线程安全的,在多线程下应该使用ConcurrentHashMap,我们将在下篇文章中介绍ConcurrentHashMap的实现原理。
欢迎关注公众号:Bug搬运小能手