A HashMap interpretation

Welcome Big Brother to Little Brother Blog 2022-09-23 07:40:00 阅读数:296

hashmapinterpretation

HashMap

一、HashMap的结构

首先我们有必要了解一下HashMap的结构:

在JDK1.7及之前的版本中,HashMapThe structure is composed of arrays(,The elements of this array are also called buckets(bucket))+ 单项链表

请添加图片描述

而在JDK1.8及之后的版本中,HashMapThe structure of the 数组+ 单项链表/红黑树

请添加图片描述

1.1 hash表

了解hash表这个数据结构,先了解一下hash函数

hash函数

hash函数就是根据keyThe value of calculates where the address should be stored,而哈希表是基于哈希函数建立的一种查找表

在HashMap的hash函数

static final int hash(Object key) {

int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

从hash()方法中,可以看出 HashMap是接收key为null的情况:

①key为null 返回hash值为0

②key不为null 返回 key的hashcode的高16位 亦或 低16; (This approach is to solve 哈希冲突)

  • 这样就完了吗?不! key!=null 得到的 并非是真正的hash值

在HashMap源码中,Any method involving elements,all elementsKey进行hash()操作,接下来是获取Key的真正的Hash值:

获取hashThere are many ways to value:像 平方取中法折叠法数字分析法Divide modulo.

其中Divide modulo是用的最多的,HashMapThis method is also used

H(key)=hash(Key.hashcode())% p (p为数组的长度)

//在HashMap中 哈希取模的 操作

H(key) = (n - 1) & hash;
//只有n为2的次方 才能有 (n - 1) & hash等价于 hash % n
//这样做的好处,采用位运算,提升效率

hash冲突

obtained from different elementshash值可能相等

一般解决hash冲突的方式:

  1. 开放地址法
  2. 链地址法 (HashMap使用的方法)
  3. 再哈希法

1.2HashMap 通过 链地址法解决Hash冲突

首先我们先了解一下HashMap元素的结构

Nodes of a one-key listNode

static class Node<K,V> implements Map.Entry<K,V> {

//实现了Map.Entry
final int hash;
final K key;
V value;
Node<K,V> next; //单向链表
public final int hashCode() {

//节点的hashcode:Key的hashcode 与 value的hashcode 进行异或
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
}

红黑树的节点Node

关于红黑树:可参考(52条消息) B树和红黑树_Beauwant to lie flat blog-CSDN博客

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {

TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
//There is a single necklace watch tree to 红黑树的方法
final void treeify(Node<K,V>[] tab){
...}
//There is also a red-black tree 还原为 Method of single necklace watch
final Node<K,V> untreeify(HashMap<K,V> map) {
...}
//红黑树 增删改查的 操作
}

二、HashMap操作

2.1 HashMap的 操作常量

public class HashMap<K,V> ... {

//The length of the default initialized array is16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//数组最大长度
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//临界值
static final int TREEIFY_THRESHOLD = 8;
//The condition for the bucket to change from a single necklace list to a red-black tree1:critical value of array length,超过64,become a red-black tree
static final int MIN_TREEIFY_CAPACITY = 64;
}

2.2HashMap的属性

transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
transient int size;
transient int modCount;
final float loadFactor;

2.2创建HashMap

  • 初始化过程,The capacity of the array is not directly determined,只能对 Threshold or load factor to limit
 public HashMap(int initialCapacity, float loadFactor) {

if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY; //Judgment exceeds the maximum value 2^30
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);//critical value to become 2的次方(Easier to hash modulus)
}
public HashMap(int initialCapacity) {

this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {

this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//HashMapNot just initialization time 对transient Node<K,V>[] table; 进行初始化
//really right table初始化 的时候在 Action when adding an element for the first time

2.3添加元素

public V put(K key, V value) {

return putVal(hash(key), key, value, (onlyIfAbsent)false,(evict) true);
}
//onlyIfAbsent: putAction if existskey一样的节点,truedo not cover false进行覆盖
//evict
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;
//(1)获取数组长度,如果table没初始化,则进行初始化(这是HashMapAppears only when an element is added for the first time after initialization)
if ((p = tab[i = (n - 1) & hash]) == null)
//(2)Find the bucket specified by the array,如果桶为空(Judging that the head node is empty),Create a new node is
tab[i] = newNode(hash, key, value, null);
else {

Node<K,V> e; K k;
//(3)如果头节点不为空,then with the head node'sKey进行比较,相同则覆盖 结束
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//(4)Determine whether the structure of the bucket is a red-black tree 通过头节点 instaceof TreeNode
//If it is, it is performed according to the operation of adding elements of the red-black tree.
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {

//(5)If not, traverse the singly linked list,遍历过程中判断Key是否equal,equal直接覆盖,Otherwise, insert at the end of the linked list
for (int binCount = 0; ; ++binCount) {

if ((e = p.next) == null) {

p.next = newNode(hash, key, value, null);
//when added at the end,To prepare a singly linked list Preparation for arborization When the linked list element reaches the critical value8时候
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;
}
Singly linked list tree operation(必须满足两个条件)
  • 条件1:The capacity of the array reaches64
  • 条件2;The number of elements in a singly linked list reaches8
 final void treeifyBin(Node<K,V>[] tab, int hash) {

int n, index; Node<K,V> e;
//①First determine whether the 条件1,If not, expand the array
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
//②达到条件1 Buckets guaranteed to be converted to red-black trees 不为空
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);
}
}
数组扩容
 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) {

//大于最大容量,Threshold value is also set to maximum 2^30,无法扩容
if (oldCap >= MAXIMUM_CAPACITY) {

threshold = Integer.MAX_VALUE;
return oldTab;
}
//新容量=旧容量*2 The critical value is also doubled
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//初始化table时,If the critical value is not0,The capacity is set to the previous threshold size
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else {
 // zero initial threshold signifies using defaults
//Threshold is not initialized,the capacity is the default16
newCap = DEFAULT_INITIAL_CAPACITY;
//The critical value is set to 0.75 * 16 =12
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {

//The critical value is still0,Then it is obtained by multiplying the load factor and the capacity
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({
"rawtypes","unchecked"})
//Formally initialize the array
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//Migrate the contents of the old array to the new array
if (oldTab != null) {

for (int j = 0; j < oldCap; ++j) {

Node<K,V> e;
if ((e = oldTab[j]) != null) {

oldTab[j] = null;//Iterate over the buckets of the old array while traversing 置为null
//Judge the head node,
if (e.next == null)
//如果是单个节点,Head node of old bucket 再hashTake the modulo to get the bucket corresponding to the new array,直接赋值过去
newTab[e.hash & (newCap - 1)] = e;
//如果是红黑树,Then split according to the operation of the red-black tree
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//If it is a singly linked list of non-single nodes,then traverse each node againhashTake the mold and put it into a new bucket
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;
}

2.4 删除元素

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;
//①先要保证hash数组非空,在保证hashThe bucket corresponding to the modulo is not empty
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;
//②Determine the head node first,If the head node does not match, traverse
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {

//③Judgment is a red-black tree 还是 单向链表,Then match the corresponding node
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);
}
}
//④match to node(不为空0)进行删除
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;
}
Two cases of red-black tree degenerating into singly linked list
  • Ⅰ移除元素 remove( ) 时,在removeTreeNode( ) 方法会检查红黑树是否满足退化条件,与结点数无关.如果红黑树根 root 为空,或者 root 的左子树/右子树为空,root.left.left 根的左子树的左子树为空,都会发生红黑树退化成链表.
final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
boolean movable) {

...//红黑树根 root 为空 ||root 的左子树/右子树为空||根的左子树的左子树为空
if (root == null || root.right == null ||
(rl = root.left) == null || rl.left == null) {

tab[index] = first.untreeify(map); // too small
return;
}
...
}
  • Ⅱ 扩容resize()时,红黑树 split tree 的节点个数 小于等于 临界值6时,会退化成链表

请添加图片描述

红黑树split()源码

UNTREEIFY_THRESHOLDis the degradation threshold6

(52条消息) HashMap中红黑树TreeNode的split()方法源码分析_mameng1998的博客-CSDN博客_hashmap split

  • 一、When data is transferred from the old array to the new array,旧数组上的数据会根据(e.hash & bit)是否等于0,重新rehashCalculating the indexes on the position in the array,分两种情况:

1、等于0时,则将该树链表头节点放到新数组时的索引位置等于其在旧数组时的索引位置,denoted as low-order area tree listlo.
2、不等于0时,则将该树链表头节点放到新数组时的索引位置等于其在旧数组时的索引位置再加上旧数组长度,记为高位区树链表hi.

  • 二、当红黑树被split分割开成为两个小红黑树后:
 1、当Small red-black tree in the lower area元素个数小于等于6时,开始去树化untreeify操作;
2、当Small red-black tree in the lower area元素个数大于6且高位区红黑树不为null时,开始树化操作(赋予红黑树的特性).
 final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {

TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
for (TreeNode<K,V> e = b, next; e != null; e = next) {

next = (TreeNode<K,V>)e.next;
e.next = null;
if ((e.hash & bit) == 0) {
//Distinguish the high and low bits of the tree linked list
if ((e.prev = loTail) == null)
//低位尾部标记为null,表示还未开始处理,此时eis the first low-order tree linked list to be processed
//节点,故e.prev等于loTail都等于null
loHead = e;//低位树链表的第一个树链表节点
else
loTail.next = e;
loTail = e;
++lc;//Count the number of elements in the low-order tree linked list
}
else {

if ((e.prev = hiTail) == null)
hiHead = e;//高位树链表的第一个树链表节点
else
hiTail.next = e;
hiTail = e;
++hc;//高位树链表元素个数计数
}
}
if (loHead != null) {
 //Small red-black tree in the lower area
if (lc <= UNTREEIFY_THRESHOLD)
//进行退化
tab[index] = loHead.untreeify(map);
else {

tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
if (hiHead != null) {
 //Small red and black tree high area
if (hc <= UNTREEIFY_THRESHOLD)
//进行退化
tab[index + bit] = hiHead.untreeify(map);
else {

tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}

2.5 HashMap清楚clear()

 public void clear() {

Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {

size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null; //很暴力,Directly assign the bucket to empty,等GC回收
}
}

三、为什么像ArrayList HashMapno scaling operation

请添加图片描述
同理对于 The critical value of red-black tree degradation is set as6而不是8原因 Also to prevent repeated horizontal jumps,Leave two locations as the cache interval

copyright:author[Welcome Big Brother to Little Brother Blog],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/266/202209230624511763.html