文章目錄
- 一、HashMap
- 1.1HashMap的實作原理:
- 1.2HashMap資料結構
- 二、HashMap
- 2.1.put()操作
- 2.2.get()操作
- 2.3.resize()操作
- 總結
- 擴展問題
一、HashMap
1.1HashMap的實作原理:
首先有一個每個元素都是鏈表(jdk1.8中滿足特定條件后鏈表轉化為紅黑樹)的陣列,當要添加一個元素(key-value)時,就首先計算元素key的hash值,然后 使用函式f(hash)=(n - 1) & hash 以此確定插入陣列中的位置,但是可能存在同一hash值的元素已經被放在陣列同一位置了,這時就添加到同一hash值的元素的后面,他們在陣列的同一位置,但是形成了鏈表,同一各鏈表上的Hash值是相同的,所以說陣列存放的是鏈表,而當鏈表長度太長時,鏈表就轉換為紅黑樹,這樣大大提高了查找的效率,
1.2HashMap資料結構
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //陣列上容器的最大個數
static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量
static final float DEFAULT_LOAD_FACTOR = 0.75f;//裝載因子
static final int TREEIFY_THRESHOLD = 8;//樹形化閾值;單個容器上鏈表長度>=8符合樹形化條件
static final int UNTREEIFY_THRESHOLD = 6;//調整大小時,單個容器上鏈表長度<6取消樹形態的閾值
static final int MIN_TREEIFY_CAPACITY = 64;//樹形化閾值;表容量>=64符合樹形化的條件
位桶資料結構(鏈表陣列)
transient Node<k,v>[] table;//存盤(位桶)的陣列</k,v>
陣列鏈表中鏈表的節點定義
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;
}
}
紅黑樹資料結構
//紅黑樹
static final class TreeNode<k,v> extends LinkedHashMap.Entry<k,v> {
TreeNode<k,v> parent; // 父節點
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;
}
}
二、HashMap
2.1.put()操作
原始碼如下(示例):
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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為慷訓者table的長度為0,則要進行擴容操作,初始擴容大小為16*/
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
/*如果table的在(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;
/*檢查第一個Node,p是不是要找的值*/
if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))
e = p;
/*檢查第一個Node,P是否是紅黑樹節點*/
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
/*處理添加沖突*/
else {
for (int binCount = 0; ; ++binCount) {
/*指標為空就掛在后面*/
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
/*如果沖突的節點數已經達到8個,看是否需要改變沖突節點的存盤結構,
treeifyBin首先判斷當前table的長度,如果不足64,只進行resize()
操作,擴容table,如果table長度達到64,那么將沖突的存盤結構為紅黑樹*/
//TREEIFY_THRESHOLD = 8
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,就是key的Value存在
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;//新值賦給當前節點
afterNodeAccess(e);
return oldValue;//回傳存在的舊Value值
}
}
++modCount;
/*如果當前大小大于門限,門限原本是初始容量*0.75*/
if (++size > threshold)
resize();//擴容兩倍
afterNodeInsertion(evict);
return null;
}
put()操作的程序
1,判斷鍵值對陣列tab[]是否為慷訓為null,否則以默認大小resize();
2,根據鍵值key計算hash值得到插入的陣列索引 i,如果tab[i]==null,直接新建節點添加,否則轉入3
3,判斷當前陣列中處理hash沖突的方式為鏈表還是紅黑樹(check第一個節點型別即可),分別處理
2.2.get()操作
代碼如下(示例):
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab;//Entry物件陣列
Node<K,V> first,e; //在tab陣列中經過散列的第一個位置
int n;
K k;
/*找到插入的第一個Node,方法是hash值和n-1相與,tab[(n - 1) & hash]*/
//也就是說在一條鏈上的hash值相同的
if ((tab = table) != null && (n = tab.length) > 0 &&(first = tab[(n - 1) & hash]) != null) {
/*檢查第一個Node是不是要找的Node*/
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
//判斷條件是hash值要相同,key值要相同
return first;
/*檢查first后面的node*/
if ((e = first.next) != null) {
//判斷是否是紅黑樹節點
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
/*遍歷后面的鏈表,找到key值和hash值都相同的Node*/
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
get()操作的程序
1.get(key)方法時獲取key的hash值,計算hash&(n-1)得到在鏈表陣列中的位置first=tab[hash&(n-1)],
2.先判斷first的key是否與引數key相等
3.不等就遍歷后面的鏈表(或紅黑樹結構)
4.找到相同的key值、相同的hash 值回傳對應的Value值即可
2.3.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
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;//newCap:擴容后的鏈表陣列容量newThr:下一次擴容的容量閾值
/*如果舊表的長度不是空*/
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
/*把新表的長度設定為舊表長度的兩倍,newCap=2*oldCap*/
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
/*把新表的門限設定為舊表門限的兩倍,newThr=oldThr*2*/
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
/*如果舊表的長度的是0,就是說第一次初始化表*/
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
/*如果新表*/
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;//把新表賦值給table
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)//說明這個node沒有鏈表直接放在新表的e.hash & (newCap - 1)位置
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
/*如果e后邊有鏈表,到這里表示e后面帶著個單鏈表,需要遍歷單鏈表,將每個結點重*/
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;//記錄下一個結點
//新表是舊表的兩倍容量,實體上就把單鏈表拆分為兩隊,
//e.hash&oldCap為偶數一隊,e.hash&oldCap為奇數一對
//分成兩隊尾插法插入
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);
//lo隊不為null,放在新表原位置
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;//結束后頭結點掛在陣列上
}
//hi隊不為null,放在新表j+oldCap位置
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;//結束后頭結點掛在陣列上
}
}
}
}
}
return newTab;
}
總結
HashMap在jdk1.8相比1.7增加了紅黑樹,以增加查詢效率,

紅黑樹使用條件
如果某個桶容器中的記錄過大的話(當前是TREEIFY_THRESHOLD = 8以及table表的長度大于64時),HashMap會動態的使用一個專門的treemap實作來替換掉它,這樣做的結果會更好,是O(logn),而不是糟糕的O(n),
擴展問題
- HashMap中的裝載因子為什么是0.75?
- HashMap執行緒安全嗎?
- HashMap實作執行緒安全有哪些操作?
- 這些操作中分別是怎么實作執行緒安全的?
- 你知道紅黑樹的原理嗎?
參考文章鏈接: https://blog.csdn.net/tuke_tuke/article/details/51588156.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/274852.html
標籤:其他
上一篇:極客日報第98期:雷軍回應小米新 Logo 爭議;馬化騰排名第 15 位,2021 全球億萬富豪榜出爐!谷歌將停止使用甲骨文的財務軟體
下一篇:pwnable_hacknote
