一、基础知识
说实话,写文章是会上瘾的,就好像小时候去游戏厅投了一个币之后,忍不住想买十个一样。自从上次笔者写了Jdk1.7HashMap与ConcurrentHashMap源码解析之后,就一直手痒想写jdk1.8的,于是就有了这篇文章。
1.1单向、双向链表结构
Jdk1.8HashMap中的TreeNode类不止有红黑树的属性parent、left、right、red,还同时存在prev和next属性。所以TreeNode即是红黑树,也是双向链表。不知道链表数据结构的读者可以自行百度,也可以看笔者之前的文章:Jdk1.7HashMap与ConcurrentHashMap源码解析(put,get详解)。
1.2二叉搜索树和红黑树
你以为jdk1.8的HashMap仅由数组和链表组成?Too young too simple。你以为红黑树很难?其实就是升级版的二叉搜索树而已。啥,你连二叉搜索树都不知道?这篇文章也许能帮助你,JAVA实现二叉搜索树和红黑树
二、HashMap源码详解
2.1大致结构
2.2属性
默认加载因子,用于扩容
static final float DEFAULT_LOAD_FACTOR = 0.75f;
最外层数组,jdk1.7是Entry<K,V>[]
transient Node<K,V>[] table;
table的默认初始化容量,值16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
最小树化容量,如果在tab[i]需要树化时,table.length<64优先选择扩容
static final int MIN_TREEIFY_CAPACITY = 64;
扩容红黑树时拆分链表解除树化的长度临界值
static final int UNTREEIFY_THRESHOLD = 6;
2.3无参构造
和JDK1.7不同,JDK1.8的无参构造没有调用有参构造,而只是初始花了加载因子
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
2.4put方法
2.4.1put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
2.4.2hash方法,计算hash
计算hash,想较于JDK1.7一系列位移异或操作简单了不少
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
2.4.3putVal方法
onlyIfAbsent:如果为true在插入相同的key时不会替换value。
evict:如果创建map时调用,evict为false。
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果table未初始化,则先初始化
if ((tab = table) == null || (n = tab.length) == 0)
//resize方法也可以进行扩容,详见2.4.7
n = (tab = resize()).length;
//计算插入数组的下标i,并判断tab[i]是否为空
//如果tab[i]为空直接插
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//如果tab[i]不为空
else {
Node<K,V> e; K k;
//三种情况
//情况一:tab[i]的key和要插入的key相等
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//获取旧的Node
e = p;
//情况二:tab[i]的位置是一颗红黑树
else if (p instanceof TreeNode)
//插红黑树,见2.4.4
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//情况三:tab[i]的位置为链表
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果tab[i]位置的链表已经有8个结点了,此时加上新插入的结点一共9个
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//树化,将链表转化为红黑树,见2.4.5
treeifyBin(tab, hash);
break;
}
//和情况一一样,如果key重复,获取旧Node
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)
//详见2.4.7
resize();
afterNodeInsertion(evict);
return null;
}
2.4.4putTreeVal方法,现有红黑树插入
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this;
//遍历找插入位置的父结点,不解释
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
//和treeify中的moveRootToFront,balanceInsertion方法作用一样,不解释
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
2.4.5treeifyBin方法,单向链表转双向链表
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//万一Node数组还没有初始化,先初始化
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
//如果tab[i]位置的Node不为空
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
//将Node转化为TreeNode
//TreeNode有parent,left,right,red,prev,next6个属性,这里只设置了prev和next
//实际上是先把单向链表转化为双向链表,真正生成红黑树的逻辑还在后面
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)
//Node开始转化为红黑树,见2.4.6
hd.treeify(tab);
}
}
2.4.6treeify方法,双向链表转红黑树
final void treeify(Node<K,V>[] tab) {
//声明根节点
TreeNode<K,V> root = null;
//遍历双向链表
for (TreeNode<K,V> x = this, next; x != null; x = next) {
//获取链表下一个结点
next = (TreeNode<K,V>)x.next;
//现将红黑树左右结点置空
x.left = x.right = null;
//如果跟结点为空,设置跟结点
if (root == null)
x.parent = null;
x.red = false;
root = x;
}
//根节点不为空
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
//遍历红黑树,找到应该插入的位置
for (TreeNode<K,V> p = root;;) {
//下面的代码不详细解释,相当于二叉搜索树寻找要插入结点的父结点
//比较方式为hash值得大小比较
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
//如果两个结点的hash值相等,进一步用compareComparables比较
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
//如果还是相等,用类名,hashCode,identityHashCode等进行比较
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
//调色,不详细介绍,熟悉红黑树的插入自然懂,可以参考笔者前面推荐的文章
root = balanceInsertion(root, x);
break;
}
}
}
}
//找到红黑树的根结点并指向tab[i]的位置上,代码很简单不详细介绍
moveRootToFront(tab, root);
}
2.4.7resize方法,初始化,扩容
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//如果老数组容量大于0
if (oldCap > 0) {
//如果老数组容量大于2的30次方
if (oldCap >= MAXIMUM_CAPACITY) {
//阈值等于2的31次方-1
threshold = Integer.MAX_VALUE;
return oldTab;
}
//DEFAULT_INITIAL_CAPACITY=16
//正常情况,新数组容量等老数组容量2倍
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;
//啥都没初始,容量=16,阈值等12
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//防止意外,一般不会进这个if
if (newThr == 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;
//如果oldTab[j]不为空,开始操作
if ((e = oldTab[j]) != null) {
//把oldTab[j]置空,回收内存
oldTab[j] = null;
//如果oldTab[j]只有一个元素,直接放到新数组
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
//如果oldTab[j]是一颗红黑树
else if (e instanceof TreeNode)
//详见2.4.8
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//如果oldTab[j]是大于一个元素的链表
else { // preserve order
//尝试将原链表拆成2个链表,一个放在tab[j]另一个放在tab[j + oldCap]
//下面的代码在split方法中有类似操作,详见2.4.8
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.8split方法
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
//初始化4个参数,目的在于尝试将红黑树拆成2个链表,一个放在tab[index]另一个放在tab[2*index]
//因为e.hash&bit要么等于0,要么等于1,等于0放tab[index],等于1放tab[2*index]
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
//把TreeNode当成双向链表进行遍历,尝试拆分
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)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
//拆成2个链表后,2个链表长度分别为lc和hc
//判断lc长度是否大于6,大于则树化,否则存链表
if (loHead != null) {
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {
tab[index] = loHead;
//如果hi为0,相当于没有拆,无需树化,直接移动原来整颗红黑树的指针
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
//判断hc长度是否大于6,大于则树化,否则存链表
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
//如果lo为0,相当于没有拆,无需树化,直接移动原来整颗红黑树的指针
if (loHead != null)
hiHead.treeify(tab);
}
}
}
2.5get方法
其实看懂了put方法之后,get方法就是小学课本了,下面简单讲一下
2.5.1get方法
public V get(Object key) {
Node<K,V> e;
//调用getNode,没啥好说的,见2.5.2
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
2.5.2getNode方法
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//如果table不为空或者长度大于0
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//运气好,fist的结点就是要找的,直接返回
if (first.hash == hash && // always check first node
((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;
}
2.5.3getTreeNode和find方法
因为getTreeNode实际就是调用了find方法,遂放在一起讲
final TreeNode<K,V> getTreeNode(int h, Object k) {
//判断红黑树是否还在,因为可能别的线程删除了
return ((parent != null) ? root() : this).find(h, k, null);
}
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
TreeNode<K,V> p = this;
do {
//比大小,看走左边还是走右边,最终找到hash值相等的TreeNode
//如果比较不出来,则看TreeNode的left或right是否为空
//否则和插入红黑树一样,比较类名,hashCode,identityHashCode等
int ph, dir; K pk;
TreeNode<K,V> pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if (pl == null)
p = pr;
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}
转载:https://blog.csdn.net/baidu_41650495/article/details/105239314