一、Map的整體結構概要
上述爲HashMap的內容結構,方法包含大部分常用的,沒有列舉完。
二、HashMap結構圖
1、JDK7及之前
2、JKD8及之後
由上面結構圖可知,HashMap由數組和鏈表共同構成,JDK8對HashMap做了優化,採用了紅黑樹的數據結構來做優化,使得HashMap存取速度更快。
三、HashMap實例化過程
1、幾個重要的參數
屬性名 | 屬性說明 | JDK7 | JDK8 |
---|---|---|---|
loadFactor | 加載因子,初始值=0.75,與擴容有關 | √ | √ |
threshold | 臨界值,與HashMap擴容相關 | √ | √ |
modCount | map中數據改變次數的統計 | √ | √ |
DEFAULT_INITIAL_CAPACITY | 默認的初始容量 ,=1<<4=16 | √ | √ |
MAXIMUM_CAPACITY | 最大容量,=1<<30 | √ | √ |
DEFAULT_LOAD_FACTOR | 默認加載因子,=0.75 | √ | √ |
TREEIFY_THRESHOLD | 使用TreeNode的臨界值,默認=8 | × | √ |
UNTREEIFY_THRESHOLD | 與split方法有關 | × | √ |
MIN_TREEIFY_CAPACITY | 最小TreeNode的容量爲64 | × | √ |
2、構造函數HashMap
JDK8
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
JDK7
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
this.loadFactor = loadFactor;
threshold = initialCapacity;
init();
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
比較發現最大的改變就是在無參構造函數時,JDK8僅僅是初始化loadFactor讓其等於默認值。而JDK7是調用了一個有參的構造函數,參數使用了默認值。
Map通過構造函數new一個HashMap時,其內部存儲數據的數組並沒有實例化,而是在PUT方法中去做了一件判斷table是否爲空的事,若爲空就會調用resize()方法,resize()第一次調用就會實例化一個長度爲DEFAULT_INITIAL_CAPACITY的Node[]。
四、HashMap存取put/get
1、put(K key,V value)
先來看一張流程圖:
該流程圖闡述了putVal()方法的整個執行過程。現在我們來看putVal()的源碼
//對外開發使用
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//存值的真正執行者
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
//定義一個數組,一個鏈表,n永遠存放數組長度,i用於存放key的hash計算後的值,即key在數組中的索引
Node<K,V>[] tab; Node<K,V> p; int n, i;
//判斷table是否爲空或數組長度爲0,如果爲空則通過resize()實例化一個數組並讓tab作爲其引用,並且讓n等於實例化tab後的長度
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//根據key經過hash()方法得到的hash值與數組最大索引做與運算得到當前key所在的索引值,並且將當前索引上的Node賦予給p並判斷是否該Node是否存在
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);//若tab[i]不存在,則直接將key-value插入該位置上。
//該位置存在數據的情況
else {
Node<K,V> e; K k; //重新定義一個Node,和一個k
// 該位置上數據Key計算後的hash等於要存放的Key計算後的hash並且該位置上的Key等於要存放的Key
if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))
e = p; //true,將該位置的Node賦予給e
else if (p instanceof TreeNode) //判斷當前桶類型是否是TreeNode
//ture,進行紅黑樹插值法,寫入數據
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//false, 遍歷當前位置鏈表
for (int binCount = 0; ; ++binCount) {
//查找當前位置鏈表上的表尾,表尾的next節點必然爲null,找到表尾將數據賦給下一個節點
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null); //是,直接將數據寫到下個節點
// 如果此時已經到第八個了,還沒找個表尾,那麼從第八個開始就要進行紅黑樹操作
if (binCount >= TREEIFY_THRESHOLD - 1)
//紅黑樹插值具體操作,注意:該方法不一定會將該位置的Node轉換成紅黑樹
treeifyBin(tab, hash);
break;
}
//如果當前位置的key與要存放的key的相同,直接跳出,不做任何操作
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
break;
//將下一個給到p進行逐個查找節點爲空的Node
p = e;
}
}
//如果e不爲空,即找到了一個去存儲Key-value的Node
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//當最後一次調整之後Size大於了臨界值,需要調整數組的容量
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
2、取值,請看源碼解析:
//對外公開方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//實際邏輯控制方法
final Node<K,V> getNode(int hash, Object key) {
//定義相關變量
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//保證Map中的數組不爲空,並且存儲的有值,並且查找的key對應的索引位置上有值
if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
// always check first node 第一次就找到了對應的值
if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
return first;
//判斷下一個節點是否存在
if ((e = first.next) != null) {
//true,檢測是否是TreeNode
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key); //通過TreeNode的get方法獲取值
//否,遍歷鏈表
do {
//判斷下一個節點是否是要查找的對象
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
return e;
}while ((e = e.next) != null);
}
}//未找到,返回null
return null;
}
五、HashMap擴容機制resize()
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length; //未擴容時數組的容量
int oldThr = threshold;
int newCap, newThr = 0;//定義新的容量和臨界值
//當前Map容量大於零,非第一次put值
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) { //超過最大容量:2^30
//臨界值等於Integer類型的最大值 0x7fffffff=2^31-1
threshold = Integer.MAX_VALUE;
return oldTab;
}
//當前容量在默認值和最大值的一半之間
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; //新臨界值爲當前臨界值的兩倍
}
//當前容量爲0,但是當前臨界值不爲0,讓新的容量等於當前臨界值
else if (oldThr > 0)
newCap = oldThr;
//當前容量和臨界值都爲0,讓新的容量爲默認值,臨界值=初始容量*默認加載因子
else {
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//如果新的臨界值爲0
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE);
}
//臨界值賦值
threshold = newThr;
//擴容table
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;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;//此時newCap = oldCap*2
else if (e instanceof TreeNode) //節點爲紅黑樹,進行切割操作
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { //鏈表的下一個節點還有值,但節點位置又沒有超過8
//lo就是擴容後仍然在原地的元素鏈表
//hi就是擴容後下標爲 原位置+原容量 的元素鏈表,從而不需要重新計算hash。
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 == 0 判斷元素位置是否還在原位置
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);
//循環鏈表結束,通過判斷loTail是否爲空來拷貝整個鏈表到擴容後table
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
六、幾個重點解析
//String類型 HashCode
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
//Integer類型的 HashCode ,就是value本身
public static int hashCode(int value) {
return value;
}
//HashMap中的hash(), 小於2^16的值的hashCode都是其本身
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
HashMap put與resize的實例圖
到此,HashMap中基本的實現過程就講完了,不對之處還請多多指教!
參考文獻
1、原文鏈接:https://blog.csdn.net/goosson/article/details/81029729