温馨提示:本文是直接基于jdk1.8来进行分析,是结合源码和网上的资料以及自己的理解写出来的,请放心"视"用。
开始之前先简单介绍一下HashMap:
HashMap 是一个散列表(也叫哈希表),什么是散列表呢,比较官方的问答是根据关键码值(Key value)而直接进行访问的一种数据结构,因此它存储的内容是键值对(key-value)映射。而且HashMap的底层数据结构是数组+链表+红黑树,学过java的人应该知道数组的特点是查询快、增删慢,链表的特点是增删快、查询慢,因此结合了两者之长的HashMap它的查询快、增删也快。这里的红黑树容我先卖个关子,我会在文章后面讲解HashMap什么时候会用到红黑树。
接下来就进入重点,我会从使用最多的put和get方法结合源码来分析它的实现原理
首先进入HashMap的构造方法,这里我们可以看见这样一个参数

这就是HashMap存储数据的地方,就是一个Node数组。

点击Node后我们就可以看见它里面有几个参数,看见这个Node对象里面还包含着另一个Node,这里我们是不是可以明显的感觉到这个Node对象结构就是我们所学过的单向链表,所以说HashMap的底层数据结构是数组+链表,有人会说那红黑树呢,红黑树怎么没了,这不是你自己刚刚说的吗,别急别急,至于红黑树则是一个链表达到了所对应的转换阈值就会转换成红黑树,这个在后面我再做解释。
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
// hash(key) 是为了计算这个key所对应的hashCode值
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 判断table字段是否为空,为空或者是字段长度等于0就进行初始化
if ((tab = table) == null || (n = tab.length) == 0)
// 这里的resize()方法就是进行初始化
n = (tab = resize()).length;
// 计算存储的索引位置,如果数组[i]位置没有元素,就在i位置直接赋值
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 判断当前数组的头节点是否和要存入的key以及hash值相等
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 判断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);
// 链表长度大于8,并且数组长度大于64才会转换为红黑树,至于为什么还要加上数组长度大于64,后面我会给大家解释
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 这里的判断如果为true,则表示当前链表存在这个key
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 这里为true表示找到了key在链表上对应的位置,并将该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;
/**
*能走到这一步,是那就说明放入元素的时候,这个要存储的key对应的位置是没有元素的,
*所以相当于数组中添加了一个新的元素,因此这里有判断是否需要resize方法进行扩容 和返回空值
*/
// 判断是否需要扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}来稍微总结一下put方法的实现过程:首先进入put方法后先调用hash方法计算出hash值,然后判断数组table是否为空,为空就进行初始化。然后通过((n - 1) & hash)找到所对应的数组下标,如果这个下标位置没有值则直接添加,若有值则先判断当前位置头节点的key和hash值是否相等,相等就会覆盖当前的value值,并返回被覆盖的value值。若不相等则继续遍历这个头节点后面所有节点,相等就会覆盖当前的value值,并返回被覆盖的value值。若都不相等则会添加到该数组下标位置所对应链表的末尾,然后判断是否需要转换成红黑树,并返回null。
put方法到这里就讲完了,但是上面还有一个遗留的小问题,关于链表转换红黑树的阈值为什么除了链表长度大于8之外还需要数组长度大于64呢?这里我们进入到treeifyBin方法中看看就知道怎么回事了。


一进入treeifyBin方法我们就可以看见他有一个判断,当这个数组为空或者是这个数组的长度小于64时就会进行扩容,而不会转换成红黑树,因此我们可以知道链表转换成红黑树的阈值除了链表长度大于8之外还有就是数组长度需要大于64。
接下来就让我们继续来看一下get方法
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
// 首先通过hash方法计算出key的hash值,然后调用getNode方法
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// 判断数组是否为空,判断数组长度是否大于0,判断(n - 1) & hash所对应的数组位置下是否有值
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);
// 遍历后面的链表,找到key值和hash值都相同的Node节点
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}可以看见get方法的实现过程大致是首先通过hash方法计算出key所对应的hash值,然后通过hash值找到所对应的数组下标(就是这个 (n - 1) & hash),然后若当前数组下标位置没有值,则直接返回null,若有值则先检查该位置的头节点是否就是我们要找的节点,是就直接返回,不是则循环遍历头节点后的所有节点,若找到相等的节点则直接返回,结束getNode方法,没找到就返回为null。
好了,以上就是我对HashMap的get和put方法底层实现原理的简单理解了,如有问题,还请大家指正。
