系列文章目錄
[Java基礎(chǔ)] StringBuffer 和 StringBuilder 類應(yīng)用及源碼分析
[Java基礎(chǔ)] 數(shù)組應(yīng)用及源碼分析
[Java基礎(chǔ)] String,分析內(nèi)存地址,源碼
[JDK8環(huán)境下的HashMap類應(yīng)用及源碼分析] 第一篇 空構(gòu)造函數(shù)初始化
[JDK8環(huán)境下的HashMap類應(yīng)用及源碼分析] 第二篇 看源碼了解HashMap的擴(kuò)容機(jī)制
[JDK8環(huán)境下的HashMap類應(yīng)用及源碼分析] 第三篇 修改capacity實(shí)驗(yàn)
[JDK8環(huán)境下的HashMap類應(yīng)用及源碼分析] 第四篇 HashMap哈希碰撞、HashMap存儲(chǔ)結(jié)構(gòu)、鏈表變紅黑樹
1、JDK8下的HashMap的數(shù)據(jù)結(jié)構(gòu)
HashMap是一種基于數(shù)組和鏈表(或紅黑樹)的數(shù)據(jù)結(jié)構(gòu),它通過哈希函數(shù)將鍵映射到數(shù)組的一個(gè)位置,并在該位置存儲(chǔ)一個(gè)鍵值對(duì)的節(jié)點(diǎn)。
HashMap的put方法在插入數(shù)據(jù)前,首先要計(jì)算鍵的哈希值(hash(key))和索引,然后在相應(yīng)的位置插入或更新節(jié)點(diǎn),如果節(jié)點(diǎn)數(shù)超過閾值(threshold),就會(huì)進(jìn)行擴(kuò)容(resize())或樹化。
HashMap的get方法主要是根據(jù)鍵的哈希值和索引,找到對(duì)應(yīng)的位置,然后遍歷鏈表或紅黑樹,返回匹配的值。
1.1、hash
public class HashMap {
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
}
public class Object {
public native int hashCode();
}
public final class System {
/**
* Returns the same hash code for the given object as
* would be returned by the default method hashCode(),
* whether or not the given object's class overrides
* hashCode().
* The hash code for the null reference is zero.
*
* @param x object for which the hashCode is to be calculated
* @return the hashCode
* @since JDK1.1
*/
public static native int identityHashCode(Object x);
}
下文引用自:深入解析Java對(duì)象和類在HotSpot VM內(nèi)部的具體實(shí)現(xiàn)
對(duì)象哈希值
_mark中有一個(gè)hash code字段,表示對(duì)象的哈希值。每個(gè)Java對(duì)象都有自己的哈希值,如果沒有重寫Object.hashCode()方法,那么虛擬機(jī)會(huì)為它自動(dòng)生成一個(gè)哈希值。哈希值生成的策略如代碼清單3-4所示:
代碼清單3-4 對(duì)象hash值生成策略
static inline intptr_t get_next_hash(Thread * Self, oop obj) {
intptr_t value = 0; if (hashCode == 0) { // Park-Miller隨機(jī)數(shù)生成器 value =
os::random(); } else if (hashCode == 1) { // 每次STW時(shí)生成stwRandom做隨機(jī)
intptr_t addrBits = cast_from_oop
Java層調(diào)用Object.hashCode()或者System.identityHashCode(),最終會(huì)調(diào)用虛擬機(jī)層的runtime/synchronizer的get_next_hash()生成哈希值。
1.2、key、value類型
static final int TREEIFY_THRESHOLD = 8; //鏈表轉(zhuǎn)紅黑樹
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)
//如果是,調(diào)用 resize() 方法,進(jìn)行初始化并賦值
n = (tab = resize()).length;
//通過hash獲取下標(biāo),如果數(shù)據(jù)為null
if ((p = tab[i = (n - 1) & hash]) == null)
// tab[i]下標(biāo)沒有值,創(chuàng)建新的Node并賦值
tab[i] = newNode(hash, key, value, null);
else {
//tab[i] 下標(biāo)的有數(shù)據(jù),發(fā)生碰撞
Node<K,V> e; K k;
//判斷tab[i]的hash值和傳入的hash值相同,tab[i]的的key值和傳入的key值相同
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//如果是key值相同直接替換即可
e = p;
else if (p instanceof TreeNode)//判斷數(shù)據(jù)結(jié)構(gòu)為紅黑樹
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {//數(shù)據(jù)結(jié)構(gòu)是鏈表
for (int binCount = 0; ; ++binCount) {
//p的下一個(gè)節(jié)點(diǎn)為null,表示p就是最后一個(gè)節(jié)點(diǎn)
if ((e = p.next) == null) {
//創(chuàng)建新的Node節(jié)點(diǎn)并插入鏈表的尾部
p.next = newNode(hash, key, value, null);
//當(dāng)元素>=8-1,鏈表轉(zhuǎn)為樹(紅黑樹)結(jié)構(gòu)
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果key在鏈表中已經(jīng)存在,則退出循環(huán)
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
//更新p指向下一個(gè)節(jié)點(diǎn),繼續(xù)遍歷
p = e;
}
}
//如果key在鏈表中已經(jīng)存在,則修改其原先key的value值,并且返回老的value值
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);//替換舊值時(shí)會(huì)調(diào)用的方法(默認(rèn)實(shí)現(xiàn)為空)
return oldValue;
}
}
++modCount;//修改次數(shù)
//根據(jù)map值判斷是否要對(duì)map的大小擴(kuò)容
if (++size > threshold)
resize();
afterNodeInsertion(evict);//插入成功時(shí)會(huì)調(diào)用的方法(默認(rèn)實(shí)現(xiàn)為空)
return null;
}
查看putVal源碼,key、vlaue數(shù)據(jù)類型使用泛型,任意引用類型都可以(Java基礎(chǔ)類型不可以,因?yàn)榛緮?shù)據(jù)類型不能調(diào)用其hashcode()方法和equals()方法,進(jìn)行比較,所以HashMap集合的key只能為引用數(shù)據(jù)類型,不能為基本數(shù)據(jù)類型,可以使用基本數(shù)據(jù)類型的包裝類,例如Integer、Double、Long、Float等)。
1.3、Node
見【1.2】代碼部分,tab變量的類型Node,實(shí)現(xiàn)了Map.Entry接口
Node里有hash、key、value等屬性,也有next下一個(gè)節(jié)點(diǎn)變量(鏈表)
Node實(shí)現(xiàn)了toString、hashCode、equals等方法;
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
interface Entry<K,V> {
K getKey();
V getValue();
V setValue(V value);
boolean equals(Object o);
int hashCode();
public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> c1.getKey().compareTo(c2.getKey());
}
public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> c1.getValue().compareTo(c2.getValue());
}
public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
Objects.requireNonNull(cmp);
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
}
public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp){
Objects.requireNonNull(cmp);
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
}
}
1.4、TreeNode
見【1.2】代碼部分,p變量的類型TreeNode,實(shí)現(xiàn)了LinkedHashMap.Entry接口
TreeNode里有red等屬性,也有parent、left、right、prev等變量(紅黑樹)
TreeNode實(shí)現(xiàn)了treeify、find、putTreeVal等方法
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;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
...
}
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
TreeNode<K,V> p = this;
do {
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;
}
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
static int tieBreakOrder(Object a, Object b) {
int d;
if (a == null || b == null ||
(d = a.getClass().getName().
compareTo(b.getClass().getName())) == 0)
d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
-1 : 1);
return d;
}
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;;) {
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
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;
}
}
}
}
moveRootToFront(tab, root);
}
final Node<K,V> untreeify(HashMap<K,V> map) {
Node<K,V> hd = null, tl = null;
for (Node<K,V> q = this; q != null; q = q.next) {
Node<K,V> p = map.replacementNode(q, null);
if (tl == null)
hd = p;
else
tl.next = p;
tl = p;
}
return hd;
}
/**
* Tree version of putVal.
*/
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;
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
boolean movable) {
...
}
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
...
}
/* ------------------------------------------------------------ */
// Red-black tree methods, all adapted from CLR
static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
TreeNode<K,V> p) {
...
return root;
}
static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
TreeNode<K,V> p) {
...
return root;
}
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
TreeNode<K,V> x) {
...
}
static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
TreeNode<K,V> x) {
...
}
static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
...
return true;
}
}
1.5、插入數(shù)據(jù)時(shí)的數(shù)據(jù)結(jié)構(gòu)變化
見【1.2】代碼,在插入數(shù)據(jù)時(shí),數(shù)據(jù)結(jié)構(gòu)有什么變化呢?
效果圖可見【1】里的第二張圖
- 判斷table是否初始化
是->調(diào)用 resize() 方法,進(jìn)行初始化并賦值 - 如果不是初始化,通過hash獲取下標(biāo),如果數(shù)據(jù)為null
tab[i]下標(biāo)沒有值,創(chuàng)建新的Node并賦值 - tab[i] 下標(biāo)的有數(shù)據(jù),發(fā)生hash碰撞,有3種情況
1、判斷tab[i]的hash值和傳入的hash值相同,tab[i]的的key值和傳入的key值相同
如果相同,直接替換
2、判斷數(shù)據(jù)結(jié)構(gòu)為紅黑樹
調(diào)用紅黑樹的數(shù)據(jù)插入函數(shù)putTreeVal
3、數(shù)據(jù)結(jié)構(gòu)是鏈表
循環(huán)鏈表,如果p的下一個(gè)節(jié)點(diǎn)為null,表示p就是最后一個(gè)節(jié)點(diǎn),此時(shí)在尾部插入新Node節(jié)點(diǎn),如果此時(shí)元素個(gè)數(shù)大于等于7,鏈表轉(zhuǎn)為紅黑樹結(jié)構(gòu)
如果key在鏈表中已經(jīng)存在,則退出循環(huán)
2、實(shí)驗(yàn)
實(shí)驗(yàn)里包括哈希碰撞和鏈表變紅黑樹,讓我們一步步Debug跟蹤源代碼探個(gè)究竟
2.1、哈希碰撞
2.1.1、與位運(yùn)算(&)
- 1、計(jì)算字符串"A" , “B” , “C” , “D” , “E” , “F” , “G” , "H"的hashCode
- 2、轉(zhuǎn)換為2進(jìn)制(https://jisuan5.com/decimal/?hex=356573597)
十進(jìn)制的15轉(zhuǎn)換2進(jìn)制,結(jié)果:1111
此實(shí)驗(yàn)中"A"的hashCode=356573597,十進(jìn)制的356573597轉(zhuǎn)換2進(jìn)制,結(jié)果:10101010000001110000110011101
356573597 & 15
= 10101010000001110000110011101 & 1111
= 10101010000001110000110011101 &
00000000000000000000000001111(高位補(bǔ)碼0,對(duì)齊左邊的數(shù)據(jù))
= 00000000000000000000000001101 = 1101(高位的0可以省略掉) - 3、經(jīng)過多次把15(2的4次方-1)改為其他數(shù)據(jù)的實(shí)驗(yàn),我們發(fā)現(xiàn)2的冪次方-1,低位都是1,在做與位運(yùn)算時(shí),數(shù)據(jù)會(huì)平均分布;改為2的冪次方或其他數(shù)據(jù),低位存在0,最終數(shù)據(jù)分布不均勻;
int n = 16 - 1; //二進(jìn)制: 1111
String[] strs = { "A" , "B" , "C" , "D" , "E" , "F" , "G" , "H"};
for (int i = 0; i < strs.length; i++) {
System.out.println("-------------------------");
System.out.println(System.identityHashCode(strs[i]) );
System.out.println("二進(jìn)制:"+ Integer.toBinaryString(System.identityHashCode(strs[i])) );
System.out.println( System.identityHashCode(strs[i]) & n );
System.out.println("-------------------------");
}
-------------------------
356573597
二進(jìn)制:10101010000001110000110011101
13
-------------------------
-------------------------
1735600054
二進(jìn)制:1100111011100110010011110110110
6
-------------------------
-------------------------
21685669
二進(jìn)制:1010010101110010110100101
5
-------------------------
-------------------------
2133927002
二進(jìn)制:1111111001100010010010001011010
10
-------------------------
-------------------------
1836019240
二進(jìn)制:1101101011011110110111000101000
8
-------------------------
-------------------------
325040804
二進(jìn)制:10011010111111011101010100100
4
-------------------------
-------------------------
1173230247
二進(jìn)制:1000101111011100001001010100111
7
-------------------------
-------------------------
856419764
二進(jìn)制:110011000010111110110110110100
4
-------------------------
2.1.2、哈希碰撞
在【2.1.1】的代碼案例中,F(xiàn)、H的哈希值與15進(jìn)行與位運(yùn)算后,值都是4,詳細(xì)解釋見【1.5】, 相當(dāng)于計(jì)算在HashMap里的索引位置
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
...
if ((p = tab[i = (n - 1) & hash]) == null)
...
}
在此給出幾種解決哈希碰撞(哈希沖突)的解決辦法:
- 鏈地址法
遇到哈希碰撞的數(shù)據(jù),在數(shù)組里索引相同,然后使用鏈表去存儲(chǔ)發(fā)生碰撞的數(shù)據(jù)(JDK8的HashMap采用的此方法,且使用的尾插法)。 - 再哈希法
當(dāng)遇到哈希碰撞問題時(shí),在此哈希,直到?jīng)_突不在產(chǎn)生,這種方法不易產(chǎn)生聚集,但是增加了計(jì)算時(shí)間 - 開放地址法
當(dāng)遇到哈希碰撞問題時(shí),從發(fā)生沖突的那個(gè)單元起,按照一定的次序,從哈希表中找到一個(gè)空閑的單元。然后把發(fā)生沖突的元素存入到該單元的一種方法。 - 建立公共溢出區(qū)
將哈希表分為公共表和溢出表,當(dāng)溢出發(fā)生時(shí),將所有溢出數(shù)據(jù)統(tǒng)一放到溢出區(qū)
2.2、鏈表變紅黑樹
給定2個(gè)假設(shè)(在HashMap里,默認(rèn)加載因子0.75,在大于12(16*0.75=12)長(zhǎng)度時(shí)就會(huì)擴(kuò)容成32,與位運(yùn)算重新計(jì)算值也會(huì)變更,重新均衡的分布,詳細(xì)解釋見【1.5】)文章來源:http://www.zghlxwxcb.cn/news/detail-687007.html
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
...
//p的下一個(gè)節(jié)點(diǎn)為null,表示p就是最后一個(gè)節(jié)點(diǎn)
if ((e = p.next) == null) {
//創(chuàng)建新的Node節(jié)點(diǎn)并插入鏈表的尾部
p.next = newNode(hash, key, value, null);
//當(dāng)元素>=8-1,鏈表轉(zhuǎn)為樹(紅黑樹)結(jié)構(gòu)
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
...
}
1、哈希桶不擴(kuò)容;
2、(F、H…H8 ) & 15 都等于4,總共9個(gè)元素,在第7個(gè)元素加入時(shí),會(huì)觸發(fā)鏈表轉(zhuǎn)紅黑樹,H7、H8插入時(shí),直接走紅黑樹插入邏輯文章來源地址http://www.zghlxwxcb.cn/news/detail-687007.html
到了這里,關(guān)于[JDK8下的HashMap類應(yīng)用及源碼分析] 數(shù)據(jù)結(jié)構(gòu)、哈希碰撞、鏈表變紅黑樹的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!