首先我们有必要了解一下HashMap的结构:
在JDK1.7及之前的版本中,HashMap的结构是由数组(,这个数组的元素也称为桶(bucket))+ 单项链表
而在JDK1.8及之后的版本中,HashMap的结构则由 数组+ 单项链表/红黑树
了解hash表这个数据结构,先了解一下hash函数
hash函数就是根据key的值计算出应该存储地址的位置,而哈希表是基于哈希函数建立的一种查找表
在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; (这种方式是为了解决 哈希冲突)
在HashMap源码中,但凡涉及到元素的方法,都要对元素的Key进行hash()操作,接下来是获取Key的真正的Hash值:
获取hash值的方式有很多:像
平方取中法
、折叠法
、数字分析法
、相除取模法
。其中
相除取模
是用的最多的,HashMap也用的正是该方法H(key)=hash(Key.hashcode())% p (p为数组的长度)
//在HashMap中 哈希取模的 操作
H(key) = (n - 1) & hash; //只有n为2的次方 才能有 (n - 1) & hash等价于 hash % n //这样做的好处,采用位运算,提升效率
不同元素获取到的hash值可能相等
一般解决hash冲突的方式:
首先我们先了解一下HashMap元素的结构
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);
}
}
关于红黑树:可参考(52条消息) B树和红黑树_Beau想躺平的博客-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;
//有一个将单项链表 树化为 红黑树的方法
final void treeify(Node<K,V>[] tab){...}
//也有一个将红黑树 还原为 单项链表的方法
final Node<K,V> untreeify(HashMap<K,V> map) {...}
//红黑树 增删改查的 操作
}
public class HashMap<K,V> ... {
//默认初始化数组的长度为16
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;
//桶由单项链表变为红黑树的条件1:数组长度的临界值,超过64,就可以变为红黑树
static final int MIN_TREEIFY_CAPACITY = 64;
}
transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
transient int size;
transient int modCount;
final 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; //判断超过最大值 2^30
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);//临界值要变为 2的次方(便于进行哈希取模)
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//HashMap刚初始化时并没有 对transient Node[] table; 进行初始化
//正真对 table初始化 的时候在 第一次添加元素时操作
public V put(K key, V value) {
return putVal(hash(key), key, value, (onlyIfAbsent)false,(evict) true);
}
//onlyIfAbsent: put操作如果存在key一样的节点,true则不去覆盖 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没初始化,则进行初始化(这是HashMap初始化后第一次添加元素才会出现)
if ((p = tab[i = (n - 1) & hash]) == null)
//(2)找到数组指定的桶,如果桶为空(判断头节点为空),则开辟新的节点
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//(3)如果头节点不为空,则与头节点的Key进行比较,相同则覆盖 结束
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//(4)判断桶的结构是否为红黑树 通过头节点 instaceof TreeNode
//是则按照红黑树的添加元素操作进行
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//(5)不是则遍历单向链表,遍历过程中判断Key是否equal,equal直接覆盖,否则插在链表尾部
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//添加在尾部时,要进行准备单向链表 树化的准备 当链表元素达到临界值8时候
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;
}
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//①首先判断是否达到 条件1,达不到则对数组进行扩容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
//②达到条件1 保证要转换为红黑树的桶 不为空
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) {
//大于最大容量,临界值也设为最大 2^30,无法扩容
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//新容量=旧容量*2 临界值也翻倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//初始化table时,如果临界值不为0,容量设为之前临界值大小
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
//临界值没有初始化,则容量为默认的16
newCap = DEFAULT_INITIAL_CAPACITY;
//临界值也设为 0.75 * 16 =12
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;//边遍历边对旧数组的桶 置为null
//对头节点进行判断,
if (e.next == null)
//如果是单个节点,将旧桶的头节点 再hash取模获取新数组对应的桶,直接赋值过去
newTab[e.hash & (newCap - 1)] = e;
//如果是红黑树,则按照红黑树的操作进行分裂
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//如果是非单个节点的单向链表,则遍历对每个节点进行再次hash取模放入新的桶中
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;
}
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数组非空,在保证hash取模对应的桶非空
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);
}
}
//④匹配到节点(不为空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;
}
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;
}
...
}
UNTREEIFY_THRESHOLD为退化临界值6
(52条消息) HashMap中红黑树TreeNode的split()方法源码分析_mameng1998的博客-CSDN博客_hashmap split
1、等于0时,则将该树链表头节点放到新数组时的索引位置等于其在旧数组时的索引位置,记为低位区树链表lo。
2、不等于0时,则将该树链表头节点放到新数组时的索引位置等于其在旧数组时的索引位置再加上旧数组长度,记为高位区树链表hi。
1、当低位区小红黑树元素个数小于等于6时,开始去树化untreeify操作;
2、当低位区小红黑树元素个数大于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) {//区分树链表的高低位
if ((e.prev = loTail) == null)
//低位尾部标记为null,表示还未开始处理,此时e是第一个要处理的低位树链表
//节点,故e.prev等于loTail都等于null
loHead = e;//低位树链表的第一个树链表节点
else
loTail.next = e;
loTail = e;
++lc;//低位树链表元素个数计数
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;//高位树链表的第一个树链表节点
else
hiTail.next = e;
hiTail = e;
++hc;//高位树链表元素个数计数
}
}
if (loHead != null) { //低位区小红黑树
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) { //高位区小红黑树
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; //很暴力,直接将桶赋值为空,等GC回收
}
}