Java8 HashMap
关于jdk 8 中hashmap的知识总结讲围绕着下面的几个问题来开展, 带着问题来一步一步探索未知。
-
1、key的hashcode取模来得到数组的下标
-
2、hashmap的初始化大小
-
3、什么时候转化为红黑树
-
4、什么时候会扩容
-
5、hashmap在构造器中是没有初始化的
-
6、如何 put元素
-
7、如何 get元素
-
8、负载因子 为何 是 0.75
-
9、容量为何 都是2 的次幂
-
10、hashmap的存储结构
存储结构
在jdk 1.8之后采用的是数组 + 链表 + 红黑树 的形式来存储, 其中数组中存储的是一个桶, 并且是通过散列映射来存储键值对,在对数据的查询上使用散列码, 主要操作是对key的hashcode 进行一个取模的操作得到数组的下标,从而确定存储元素的位置, 此外hashmap 允许一个 key是null , 它是一个线程不安全的容器,在排序上面也是无序的。数组下标相同的key会被放在一个链表中存储, 链表长度达到一定值后会转化为红黑树, 并且红黑树在满足在一定条件的时候会再次退回链表。
- 结构为 数组+ 链表 + 红黑树
- 数组中存放的是一个单链表
- 并且允许一个key是nul
- 元素是无序排列的
- 链表达到一定条件会转化为红黑树
构造函数
初始化一个 HashMap
在HashMap的初始化中可以看到几个初始化数据 initialCapacity loadFactor
- loadFactor 负载因子
- initialCapacity 初始化大小
// 自定义大小以及负载因子
public HashMap(int initialCapacity
, float loadFactor) {
if (initialCapacity < 0) {
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
} else {
if (initialCapacity > 1073741824) {
initialCapacity = 1073741824;
}
if (loadFactor > 0.0F && !Float.isNaN(loadFactor)) {
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
} else {
throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
}
}
}
// 默认的负载因子
public HashMap(int initialCapacity) {
this(initialCapacity, 0.75F);
}
// 默认的负载因子
public HashMap() {
this.loadFactor = 0.75F;
}
put过程
put 方法
可以看到 put元素的时候调用的是 putVal 函数, 并且把对 key 取了一次hash, 作为参数传递了过去。
// 得到hash值的函数
public V put(K key, V value) {
return this.putVal(hash(key), key, value, false, true);
}
hash(Object key)
计算出hash 值的函数 可以看到是 使用 key 的hashcode 与hash的高16位做与运算。
static final int hash(Object key) {
int h;
return key == null ? 0 : (h = key.hashCode()) ^ h >>> 16;
}
putVal
从这一段源码中我们可以得到的信息为:
-
hashmap的在put值的时候开始初始化的。
-
hashmap计算 hash的时候是通过 key的hashcode值 与自身的高16位做与运算得到的。
-
数组下标的位置是通过 n - 1 & hash - > 容量 -1 与 hash与运算得到的,此时这点还揭示了 容量为什么是 2 的次幂。 2的次幂-1 得到的数字低位全部都是 1
-
每次添加元素是添加到链表的尾部
-
并且如果 链表的长度 大于 8 会尝试调用 treeifyBin 方法 转化红黑树
-
当前容量大于 扩容的阈值, 就会尝试扩容
-
阈值的定义: threshold: The next size value at which to resize (capacity * load factor).
-
容量的定义: size : The number of key-value mappings contained in this map.
-
存在相同key的处理方法
- 最初 会拿当前hash位置的第一个元素 对比是否出现重复 找到重复元素
- 之后 会在遍历当前hash位置所在链表的时候 对比是否出现重复 找到重复元素
- 复写找到的重复元素
// 数组的下标是这个公式计算得出的 i = n - 1 & hash
// 其实这也是为什么 hashmap的容量必须是2的次幂的原因, 2的次幂-1 得到的数字低位全部都是 1
// 此时的与运算得到的就是 % 后的结果, 更加高效
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 和后续的扩容有些不一样,因为这次是数组从 null 初始化到默认的 16 或自定义的初始容量
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// i = (n - 1) & hash 元素在数组中的下标
// 判断当前位置是否存在元素, 不存在就新建立节点, 存放。
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
// 不存在元素。
Node<K,V> e; K k;
// 判断当前hash 位置的第一个元素的hash 是否与 将要存放元素的hash相同 并且
// 当前hash 位置的第一个元素的 key 也要和 将要存放元素的 key 相同 满足的话就取出当前的元素 p 把它赋值给 e , 别忘记了此时是在链表上面操作, 当前hash位置的链表中还有其他元素
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 {
// 此时hashmap还是按照链表的方式存储, 此时遍历链表
for (int binCount = 0; ; ++binCount) {
// 这里会把要插入的元素放到 当前链表的最后面
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;
}
}
// 存在相同的key就覆盖掉。
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 当前容量大于 扩容的阈值, 就会尝试扩容
// threshold: The next size value at which to resize (capacity * load factor).
// size : The number of key-value mappings contained in this map.
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
扩容机制
初始化分析
resize() 的初始化作用分析
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
**注释: 初始化或者双倍表的大小, 如果是空的话 则在符合场阈值内的初始容量目标。 否则因为我们使用的是二次展开的能力(扩容两倍)**每个bin中的元素必须保持在同一索引中,或者移动在新表中有两个偏移量的幂。
扩容方法很长!!! 首先先分析初始化的过程~得到信息
- 会使用默认的负载因子和阈值来计算出容量
- DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
- newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 12
- 会使用默认的扩容阈值 DEFAULT_LOAD_FACTOR = 0.75f;
- 在初始化之后, 当前 map的阈值也会被初始化
- newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 12
- threshold = newThr;
final Node<K,V>[] resize() {
// 旧的 hashmap
Node<K,V>[] oldTab = table;
// 判断是否为 0
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 得到阈值, 如果是初始化的话 oldThr 是个空
int oldThr = threshold;
int newCap, newThr = 0;
// 扩容 走的代码
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 {
// 开始初始化 大小为 16 阈值为 12
// DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// DEFAULT_LOAD_FACTOR = 0.75f;
newCap = DEFAULT_INITIAL_CAPACITY; // 16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 12
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
// 定义阈值
// newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 12
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
// 新建 返回初始化的map
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;
}
扩容分析
final Node<K,V>[] resize() {
// 旧的 hashmap
Node<K,V>[] oldTab = table;
// 判断是否为 0
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 得到阈值, 如果是初始化的话 oldThr 是个空
int oldThr = threshold;
int newCap, newThr = 0;
// 扩容 走的代码 得到 原始 map的容量!
// 注意此时又进行了判断!!
if (oldCap > 0) {
// 此时容量已经很大的时候 (1073741824), 就直接一次把扩容的阈值调节到最大!!! 直接返回原来的map
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 此时容量已经大于 DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 并且也没有到达一个很大的值
// 把newThr 阈值调节到一倍大小 也就意味者扩容了一倍
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 此时就h是扩容一倍后的大小了
newCap = oldThr;
else {
// 开始初始化 大小为 16 阈值为 12
// DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// DEFAULT_LOAD_FACTOR = 0.75f;
newCap = DEFAULT_INITIAL_CAPACITY; // 16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 12
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
// 定义阈值
// newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 12
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
// 新建 返回初始化的map
// 扩容时 走到这里, 就是新建立一个 双倍大小的map
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;
}
get方法
get(Object key)
会根据 key的 hash得到元素并返回
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
getNode(int hash, Object key)
final HashMap.Node<K, V> getNode(int hash, Object key) {
HashMap.Node[] tab;
HashMap.Node first;
int n;
if (
//不为空
(tab = this.table) != null
&&
//不为空
(n = tab.length) > 0
&&
// n - 1 & hash 得到元素的下标
// n : 大小
// hash : key的hash值
// 第一个元素不是空的
(first = tab[n - 1 & hash]) != null
) {
Object k;
// 第一个元素就是我们要找的, 直接返回!!!
// 和判断元素是否重复时候类似, 先判断第一个
if (first.hash == hash && ((k = first.key) == key || key != null && key.equals(k))) {
return first;
}
HashMap.Node e;
// 下一个元素不是空的
if ((e = first.next) != null) {
// 如果此时已经是红黑树了, 依次遍历
if (first instanceof HashMap.TreeNode) {
return ((HashMap.TreeNode)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;
}
回答最初的问题
1、如何得到数组的下标
> hash
此方法用计算元素的hash值的。简单分析:
- 如果 key是一个空, 此时他的 hash 为 0
- 如果不是空值
- 拿到它的 hashCode 赋给 H
- 并且 与自身的高16位相与计算
static final int hash(Object key) {
int h;
return key == null ? 0 : (h = key.hashCode()) ^ h >>> 16;
}
计算索引下标
得到 hash 值后 便是计算索引下标的步骤
p = tab[i = (n - 1) & hash])
如果map的长度是 length 那index的值就从 0 ~ length-1。所以index需要尽可能的平衡,也就是分布均匀,不能某些位置上存储特别多的数据,某些位置上又特别少。 解决办法:
- 取模计算
- hash值为int,index需要映射到0 ~ length -1,最直观的使用取模运算, index = hash值 % length
- 位运算
- (n - 1) & hash
肯定是位运算的效率比较高!!!注意此时 n -1 是一个奇数
举例
index = HashCode(Key) & (Length - 1)
以值为“book”的Key来演示整个过程:
-
计算book的hashcode,结果为十进制的3029737,二进制的101110001110101110 1001。
-
假定HashMap长度是默认的16,计算Length-1的结果为十进制的15,二进制的1111。
-
把以上两个结果做与运算,101110001110101110 1001 & 1111 = 1001,十进制是9,所以 index=9。
可以说,Hash算法最终得到的index结果,完全取决于Key的Hashcode值的最后几位。
长度16或者其他2的幂,Length-1的值是所有二进制位全为1,这种情况下,index的结果等同于HashCode后几位的值。只要输入的HashCode本身分布均匀,Hash算法的结果就是均匀的。
2、容量为何 都是2 的次幂
容量问题
其实这也是为什么 hashmap的容量必须是2的次幂的原因, 2的次幂-1 得到的数字低位全部都是 1
此时的与运算得到的就是 % 后的结果, 更加高效
3、hashmap的初始化大小以及阈值
初始化大小
此问题, 可以在 扩容介绍的第一部分得到答案:
- 使用默认的大小 16
- 默认的负载因子 0.75
做出乘法, 这样做的原因是为了减少扩容的次数。
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 12
4、什么时候转化为红黑树
查阅注释
Ideally, under random hashCodes, the frequency of
* nodes in bins follows a Poisson distribution
* (http://en.wikipedia.org/wiki/Poisson_distribution) with a
* parameter of about 0.5 on average for the default resizing
* threshold of 0.75, although with a large variance because of
* resizing granularity. Ignoring variance, the expected
* occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
* factorial(k)). The first values are:
*
* 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
* more: less than 1 in ten million
*
从上表可以看出当桶中元素到达8个的时候,概率已经变得非常小,也就是说用0.75作为负载因子,每个碰撞位置的链表长度超过8个是几乎不可能的。(也就是超过8 可以转化为红黑树)
- 并且如果 链表的长度 大于 8 会尝试调用 treeifyBin 方法
- 在此判断 表的长度是否大于64
在链表长度大于 8 并且 表的长度大于 64 的时候会转化红黑树!!!!
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;
}
treeifyBin
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// 如果表的长度小于 64 会先扩容!!! 否则 扩容
// MIN_TREEIFY_CAPACITY = 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);
}
}
5、什么时候会扩容
treeifyBin
接上面的分析
- 在链表长度大于 8 并且 表的长度小于 64 的时候会扩容
putVal
- 初始化元素的时候会调用 resize方法
- 当表的容量大于 扩容的阈值时候
并且扩容是直接新建一个map
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if (++size > threshold)
resize();
6、hashmap在什么时候初始化
putVal
在第一次向 map中添加元素的时候, 会调用 resize() 方法, 此时会采用默认的值来初始化 map
- 默认的阈值
- 默认的容量
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
resize()
7、如何 put元素
上述分析
8、如何 get元素
上述分析
9、负载因子 为何 是 0.75
HashMap有一个初始容量大小,默认是16
- static final int DEAFULT_INITIAL_CAPACITY = 1 << 4; // aka 16
负载因子决定着map中数组能够存放多少个元素, 当负载因子比较大的时候, 此时数组中的元素就非常多了, 数据的密度就会上升, 每次put值的时候发生碰撞的几率就会增大!!!所以负载因子的大小需要合理的设置 此外还考虑到链表转化红黑树的原因
- 链表长度大于8 转化红黑树
这是因为在0.75 的负载因子下, 会多于出来 0.25 的密度来缓冲哈希碰撞, 在当前的数据密度下, 数组中每个位置链表长度大于8 的可能性是非常小的, 所以以 8 为阈值, 决定是否转换!
为了减少冲突概率,当HashMap的数组长度达到一个临界值就会触发扩容,把所有元素rehash再放回容器中,这是一个非常耗时的操作。而这个临界值由负载因子和当前的容量大小来决定:
-
DEFAULT_INITIAL_CAPACITYDEFAULT_LOAD_FACTOR
即默认情况下数组长度是160.75=12时,触发扩容操作。 -
hash容器指定初始容量尽量为2的幂次方。
-
HashMap负载因子为0.75是空间和时间成本的一种折中。
查阅注释
Ideally, under random hashCodes, the frequency of
* nodes in bins follows a Poisson distribution
* (http://en.wikipedia.org/wiki/Poisson_distribution) with a
* parameter of about 0.5 on average for the default resizing
* threshold of 0.75, although with a large variance because of
* resizing granularity. Ignoring variance, the expected
* occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
* factorial(k)). The first values are:
*
* 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
* more: less than 1 in ten million
*
从上表可以看出当桶中元素到达8个的时候,概率已经变得非常小,也就是说用0.75作为负载因子,每个碰撞位置的链表长度超过8个是几乎不可能的。(也就是超过8 可以转化为红黑树)
- hash容器指定初始容量尽量为2的幂次方。
- HashMap负载因子为0.75是空间和时间成本的一种折中。
10、hashmap的存储结构
参考博客:
https://www.jianshu.com/p/4aa3bb16f36c
https://blog.csdn.net/woshimaxiao1/article/details/83661464
https://www.cnblogs.com/5200207xx/p/11101014.html