HashMap底层详解及源码分析(JDK1.8)
HashMap初识
HashMap简介
- JDK1.8中的HashMap采用的是数组+链表+红黑树的数据结构,是基于哈希表的Map实现,允许null键和null值,且最多允许一对key为null的键值对,允许多个value为null的键值对,HashMap是非线程安全的,数据排序是无序的;HashMap通过散列映射存储键值对,通过生成hash code作为数组的下标,使得查询效率较高,又通过链表数据结构使得增删的效率提高
HashMap主要的成员变量
/**
* 默认的初始化容量 - 必须为2的倍数.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 构造函数中未指定时的负载因子.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 链表向红黑树转换的阈值.
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 红黑树向链表转换的阈值.
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 当前键值对数量.
*/
transient int size;
/**
* 超过这个数量HashMap会扩容.
*/
int threshold;
/**
* Node类型的数组,又被称作Hash桶,多个Node节点组成链表
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
HashMap的构造函数
这里我们只看传入参数为初始化容量和负载因子的构造函数:
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
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);
}
其中的 tableSizeFor(initialCapacity) 方法源码:
/**
* Returns a power of two size for the given target capacity.
*/
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;
}
其含义为返回距离指定参数最近的2的整数次幂,例如: 9->16, 17->32,保证为2的整数次幂,假设传入参数为18:
int n = cap - 1;//n = 00010001
n |= n >>> 1;//n=n|(n>>>1)=00010001 | 00001000 = 00011001
n |= n >>> 2;//n=n|(n>>>2)=00011001 | 00000110 = 00011111
n |= n >>> 4;//n=n|(n>>>4)=00011111 | 00000001 = 00100000
......(右移8位和16位均无影响)
n = 00100000 = 32;
HashMap的底层实现原理
HashMap是数组+链表+红黑树的底层实现,主体是数组,链表是为了解决hash冲突而存在
HashMap的put方法
/**
* Implements Map.put and related methods.
*
* @param hash 由key计算出来的hash值
* @param key 要存储的key
* @param value 要存储的value
* @param onlyIfAbsent 如果当前位置已存在一个值,是否替换,false是替换,true是不替换
* @param evict 表是否在创建模式,如果为false,则表是在创建模式
* @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;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
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))))
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
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)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
- 首先检查table是否为空,如果为空就初始化
if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length;
-
检查存放位置是否为空,若为空则直接放入
if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null);
-
不为空则检查桶中存在的元素的key和hash都相等,直接覆盖旧value
else { Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; //存在key值和hash值相等的,直接覆盖旧value if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; }
-
判断存放该元素的链表是否转为红黑树,如果为红黑树,直接插入,此时上面条件不成立,hash值不相等,也就是key值不等(hash值是由key算出来的)
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 treeifyBin(tab, hash); break; }
-
与3相同
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; //存在key值和hash值相等的,直接覆盖旧value if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; }
-
将记录修改次数加1,判断是否需要扩容,如果需要就扩容
++modCount; if (++size > threshold) resize(); //插入后回调 afterNodeInsertion(evict);
附图(图片来自这里):
put方法中调用的treeifyBin方法
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
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);
}
}
-
如果元素数组为空或者数组长度小于树结构化的最小限制MIN_TREEIFY_CAPACITY 默认值64,对于这个值可以理解为:如果元素数组长度小于这个值,没有必要去进行结构转换;当一个数组位置上集中了多个键值对,那是因为这些key的hash值和数组长度取模之后结果相同(并不是因为这些key的hash值相同),因为hash值相同的概率不高,所以可以通过扩容的方式,来使得最终这些key的hash值在和新的数组长度取模之后,拆分到多个数组位置上
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize();
-
如果元素数组长度已经大于等于MIN_TREEIFY_CAPACITY,那么就有必要进行转换
// 根据hash值和数组长度进行取模运算后,得到链表的首节点 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); // 继续遍历链表 // 到目前为止 也只是把Node对象转换成了TreeNode对象,把单向链表转换成了双向链表 // 把转换后的双向链表,替换原来位置上的单向链表 if ((tab[index] = hd) != null) hd.treeify(tab); }
HashMap的扩容resize方法
源码图(图片来自这里):
final Node<K,V>[] resize() {
//将原来的table指针保存
Node<K,V>[] oldTab = table;
//获取原来数组的长度,oldTab为null说明还没有进行初始化
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//保存以前重构table的阈值
int oldThr = threshold;
int newCap, newThr = 0;
//oldCap > 0表示已经初始化过了
if (oldCap > 0) {
//当原来的容量已经达到最大容量的时候,将阈值设置为Integer.MAX_VALUE,这样就不会再发生重构的情况
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) //虽然还没有初始化,但是设置过了阈值,将旧的阈值设置为新的容量
newCap = oldThr;
else { //没有初始化阈值的时候采用默认算法计算阈值
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {//对应oldCap = 0 && oldThr > 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;
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)
//(newCap - 1)是一个尾部全部为1的数
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)//判断旧的节点是一个树节点,则对树进行操作,重构树或者变成链表等等
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else {
// 对原来的链表部分进行重构
Node<K,V> loHead = null, loTail = null;
Node<K,V> 所以新索引要么是原索引,要不就是原索引+oldCap = 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);
//在重新计算hash之后,因为n变为2倍,那么n-1的mask范围在高位多1bit
//对原来的链表部分进行重构
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
HashMap的get方法
final HashMap.Node<K,V> getNode(int hash, Object key) {
//定义变量
HashMap.Node<K,V>[] tab; HashMap.Node<K,V> first, e; int n; K k;
//查看数据需要满足一下条件
//1)数组不为空
//2)数组长度>0
//3)通过hash计算出该元素在数组中存放位置的索引,而且该索引处数据不为空null
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//判断该数组索引位置处第一个是否为我们要找的元素 判断条件需要满足hash 和 key 相同
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
//如果第一个就是我们要找的,直接返回即可
return first;
//如果第一个不是,我们需要循环遍历,然后找数据
if ((e = first.next) != null) {
//如果第1个的元素是红黑树类型的节点
if (first instanceof HashMap.TreeNode)
//那我们需要调用红黑树的方法查找节点
return ((HashMap.TreeNode<K,V>)first).getTreeNode(hash, key);
//如果不是,则该为链表,需要遍历查找
do {
//循环判断下一个节点的hash和key是否相同
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
//更新e为下一个
} while ((e = e.next) != null);
}
}
//没找到返回Null
return null;
}
HashMap的remove方法
HashMap有两个remove方法
-
key相同就删除
public V remove(Object key) { Node<K,V> e; return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value; }
-
key和value都相同时删除
public boolean remove(Object key, Object value) { return removeNode(hash(key), key, value, true, true) != null; }
两个remove方法都调用了removeNode方法:
/**
* Implements Map.remove and related methods.
*
* @param key的hash值
* @param key的key值
* @param 如果matchValue==false忽略value值
* @param matchValue如果为true,则必须key-value同时正确
* @param movable if false do not move other nodes while removing
* @return the node, or null if none
*/
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;
}
- tab:引用当前HashMap中的散列表
p:当前node元素
n:表示散列表的数组长度
index:寻址结果 桶位
node:删除元素
-
首先判断HashMap是否为空,不为空查找桶位上有无数据
if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) {
-
有数据查找当前结点是否为要删除的元素
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) node = p;
-
若不是则继续查找,判断是否为树结构,是红黑树调用 getTreeNode(hash, key) 方法查找
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); }
-
执行删除操作,若 matchValue == false 后面的条件无需判断
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);
-
若不是树结点则删除链表节点,且 node == p 说明删除元素正好是当前桶位元素,将当前桶位元素用下个元素代替
else if (node == p) tab[index] = node.next;
-
若删除元素不是当前桶位元素,由上可知 p.next == node ,则 p.next = node.next 表示删除
else p.next = node.next; ++modCount; --size; afterNodeRemoval(node); return node;
HashMap和HashTable的区别
- HashMap 允许 key 和 value 为 null,Hashtable 不允许
- HashMap 的默认初始容量为 16,Hashtable 为 11
- HashMap 的扩容为原来的 2 倍,Hashtable 的扩容为原来的 2 倍加 1
- HashMap 是非线程安全的,Hashtable是线程安全的
- HashMap 的 hash 值重新计算过,Hashtable 直接使用 hashCode
- HashMap 去掉了 Hashtable 中的 contains 方法
- HashMap 继承自 AbstractMap 类,Hashtable 继承自 Dictionary 类