HashMap源码分析
HashMap简介
基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。(除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变。 此实现假定哈希函数将元素适当地分布在各桶之间,可为基本操作(get 和 put)提供稳定的性能。迭代 collection 视图所需的时间与 HashMap 实例的“容量”(桶的数量)及其大小(键-值映射关系数)成比例。所以,如果迭代性能很重要,则不要将初始容量设置得太高(或将加载因子设置得太低)
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {}
从类的定义可以看到HashMap继承了AbstractMap类,并且实现了Map、Cloneable、Serializable接口
HashMap数据结构
存储数组
Node<K,V>[] table;
在java8后,使用Node类型的数组来存储键值对数据。Node是一个实现了Map.Entry接口的自定义类。
static class Node<K,V> implements Map.Entry<K,V> {}
Node的主要参数有
final int hash; //哈希值
final K key; //键
V value; //值
Node<K,V> next; //连接的下一个节点
存储方式
在java8之前,HashMap的存储方式为数组+链表,数组是HashMap的主体,链表(拉链法)是为了解决哈希碰撞(两个对象在经过哈希计算后得到的索引值相同)的情况。java8后HashMap的存储方式为数组+链表+红黑树。当HashMap中链表的长度大于8并且当前数组的长度大约64,则把索引位置上的链表转化为红黑树存储数据。提高了大量数据下的查找效率。
重要参数
默认初始容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
默认的初始容量为16,规定了默认的初始容量为2的幂。
最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
最大容量为节点数组所能开辟的最大个数,如果指定了更大的值则使用最大容量的值。
默认负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
在构造函数中如果没有显式的指定负载因子的值则使用默认的负载因子值:0.75
负载因子决定了HashMap的数据密度。负载因子越大数组装填的越满,发生碰撞的几率就会越高,负载因子越小,越容易触发扩容,经常扩容会影响程序性能。之所以选择0.75作为负载因子的默认值,根据源码中注释中所解释:
在理想情况下,使用随机哈希吗,节点出现的频率在hash桶中遵循泊松分布,并且阈值为0.75,同时给出了桶中元素的个数和概率的对照表。
0: 0.60653066
1: 0.30326533
2: 0.07581633
3: 0.01263606
4: 0.00157952
5: 0.00015795
6: 0.00001316
7: 0.00000094
8: 0.00000006
将链表转为红黑树的节点数量阈值
static final int TREEIFY_THRESHOLD = 8;
从上文桶中元素的个数和概率的对照表中可以看到,当桶中元素到达8个的时候,概率已经变得非常小,当链表的长度大于了8,并且数组长度大于64,为了查找效率就会把链表转化为红黑树。
将红黑树转为链表的节点数量阈值
static final int UNTREEIFY_THRESHOLD = 6;
当红黑树的节点个数小于6时,会把红黑树转化为链表存储
可以对容器进行红黑树化处理的最小表容量
static final int MIN_TREEIFY_CAPACITY = 64;
键值对数量
transient int size;
表示HashMap中键值对的数量
修改次数
transient int modCount;
modCount是指改变HashMap中映射的数量或修改其内部结构(例如,重新散列)的次数。
主要方法
构造方法
java8在构造方法中不再初始化Node数组的长度,而是在第一次put时初始化Node数组长度
HashMap()
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
在默认构造方法中,将负载因子初始化为默认的值–0.75
HashMap(int initialCapacity)
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
显式的定义了HashMap的存储数组的长度,并且使用默认的负载因子。但是此处并不是直接就将存储数组的长度设置为传入的initialCapacity值,而是经过一系列操作将长度设置为大于等于传入值,最接近传入值的2的指数幂。详细过程见下面一个构造函数
HashMap(int initialCapacity, float 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);
}
在此构造函数中,首先判断传入的数组长度是否小于0,若小于0的抛出异常,若大于数组的最大长度则将其设置为最大长度。继而判断负载因子是否小于等于0或是否是一个非法的小数。经过了上述判断后将负载因子设置为传入的负载因子,之后执行tableSizeFor(initialCapacity),tableSizeFor()方法如下:
static final int tableSizeFor(int cap) {
int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
在tableSizeFor()中执行了Integer.numberOfLeadingZeros()方法,Integer.numberOfLeadingZeros()方法如下:
public static int numberOfLeadingZeros(int i) {
// HD, Count leading 0's
if (i <= 0)
return i == 0 ? 32 : 0;
int n = 31;
if (i >= 1 << 16) { n -= 16; i >>>= 16; }
if (i >= 1 << 8) { n -= 8; i >>>= 8; }
if (i >= 1 << 4) { n -= 4; i >>>= 4; }
if (i >= 1 << 2) { n -= 2; i >>>= 2; }
return n - (i >>> 1);
}
numberOfLeadingZeros方法的作用是返回无符号整型i的最高非零位前面的0的个数,包括符号位在内,如果i为负数,这个方法将会返回0,符号位为1。例如,
10的二进制表示为 0000 0000 0000 0000 0000 0000 0000 1010
那么这个方法返回的就是28。
tableSizeFor()中
int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
cap为传入的数组长度,假设cap = 11,那么Integer.numberOfLeadingZeros(cap - 1)的值为28。那么n相当于-1向右无符号移动28位
int n = -1 >>> 28;
我们知道-1 的二进制为
1111 1111 1111 1111 1111 1111 1111 1111
向右移动28位后变成
0000 0000 0000 0000 0000 0000 0000 1111
则n = 15
最后函数在return时候经过判断返回n+1即16。相当于把自定义的数组长度11变成了比11大的、最接近11的2的幂,即16。
这里存在两个需要注意的点:
1)Integer.numberOfLeadingZeros(cap - 1)中为什么传入的参数为cap-1?
这是为了防止cap已经是2的幂,如果cap已经是2的幂,又没有执行减1的操作,则执行完一系列操作后返回的值会是cap值的两倍。
2)为什么数组长度一定要是2的幂?
因为在计算索引的时候 使用的是**(n - 1) & hash来决定索引,当n为2次幂时,会满足一个公式:(n - 1) & hash = hash % n**,在计算机中,位运算要比%取模要快,用位运算可以提高运算的效率。
resize()
resize是HashMap中的扩容方法,为方便理解加了部分注释,resize()代码如下:
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;//保存扩容前table的引用
int oldCap = (oldTab == null) ? 0 : oldTab.length;//保存老数组长度
int oldThr = threshold;//老数组存储阈值(容量*负载因子)
int newCap, newThr = 0;//定义新的数组大小、存储阈值大小
if (oldCap > 0) {
//当数组长度已大于最大数组长度,则返回原数组,并且将存储阈值设置为Integer的最大值
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//数组长度乘2后仍然小于最大数组长度,并且当前数组长度大于等于默认的数组长度则可扩容,将容量扩大为原来的两倍
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0)
newCap = oldThr;
else { // 当初始数组长度和初始存储阈值都为0时候,将他们赋值为默认值
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {//当只满足老阈值大于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) //若当前节点没有下一个节点就证明是一个单独的数据直接计算新的位置赋值
newTab[e.hash & (newCap - 1)] = e;//e.hash & (newCap - 1)的值为新的索引位置
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> hiHead = null, hiTail = null; //保存位移的链表
Node<K,V> next;
do {//遍历
next = e.next;
if ((e.hash & oldCap) == 0) {//此时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;
}
总结:
如果是第一次进行put元素时进行扩容会将数组的长度和存储阈值设置为默认值。扩容时首先判断数组长度翻倍后是否仍然在最大范围之内,若超过最大值则设置为最大值,然后创建新的数组,将原来数组中的元素重新根据新的数组的长度计算索引值,在进行索引计算的时候每个元素只有两种情况,在原来的位置上或者在原来的位置,例子如下:
假设原来的数组长度n=8。
8的二进制编码为:
0000 0000 0000 1000
计算数组索引的公式为(n-1) & hash,假设存在两个哈希值为别为6和14
扩容前 n = 8
6的索引计算:
0000 0000 0000 0111 ->> n-1 (7)
0000 0000 0000 0110 ->> 6
--------------------
0000 0000 0000 0110 ->> 6
14的索引计算:
0000 0000 0000 0111 ->> n-1 (7)
0000 0000 0000 1110 ->> 14
0000 0000 0000 0110 ->> 6
可以看到 6 和14 的索引都是6
进行扩容以后 n = 16
6的索引计算:
0000 0000 0000 1111 ->> n-1 (15)
0000 0000 0000 0110 ->> 6
--------------------
0000 0000 0000 0110 ->> 6
14的索引计算:
0000 0000 0000 1111 ->> n-1 (7)
0000 0000 0000 1110 ->> 14
0000 0000 0000 1110 ->> 14
可以看到6的索引值不变 还是6,但是14的索引值发生改变,改变为原来的索引+原来的数组长度。
最后根据对应的索引值把元素放入新数组之中。
put(K key, V value)
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
put方法调用了putVal方法,为方便理解加了部分注释,代码如下:
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)//如果存储数组为空或长度为0则进行扩容
n = (tab = resize()).length;//扩容 详见resize方法解释
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) // 若长度达到阈值,转换为红黑树
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)//onlyIfAbsent为true:不覆盖,false:覆盖。
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;//增加修改次数
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
remove(Object key)
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
remove方法中调用removeNode方法进行删除。
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) { // 判断是否存储数组为空或者存储数组长度为0
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k)))) //判断索引位置key是否与要删除的key相等
node = p;
else if ((e = p.next) != null) { // next不为空,则索引位置为链表或红黑树
if (p instanceof TreeNode) // 红黑树
node = ((TreeNode<K,V>)p).getTreeNode(hash, key); //红黑树中找到key相等的元素
else { // 链表
do {//遍历链表找到key相等的元素
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)))) {//matchValue为是否匹配值
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;
}
get(Object key)
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
get方法中调用getNode方法获取元素。
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) {// 判断是否存储数组为空或者存储数组长度为0
if (first.hash == hash && // 判断第一个节点
((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;
}
HashMap的遍历
//获取key集合遍历key集合再进行取值(需要二次取值效率低)
private static void method04(Map<String, Integer> map) {
for (String s : map.keySet()) {
System.out.println(s + "----" + map.get(s));
}
}
//使用Map.entrySet遍历"
private static void method03(Map<String, Integer> map) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + "----" + entry.getValue());
}
}
//使用迭代器进行遍历
private static void method02(Map<String, Integer> map) {
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while ((iterator.hasNext())){
Map.Entry<String, Integer> mapEntry = iterator.next();
System.out.println(mapEntry.getKey() + "----" + mapEntry.getValue());
}
}
//使用forEach 进行遍历
private static void method01(Map<String, Integer> map) {
map.forEach(( key, value) -> {
System.out.println(key + "----" + value);
});
}