HashMap源碼分析,hashmap源碼
我所使用的JDK版本時1.8.0_144。
HashMap是我們常用的一個資料結構,以索引值對的形式進行操作。
源碼分析如下:
//預設初始容量static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;//預設最大容量static final int MAXIMUM_CAPACITY = 1 << 30;//預設載入因子, 指雜湊表可以達到多滿的尺度static final float DEFAULT_LOAD_FACTOR = 0.75f;//實際使用的雜湊表transient Node<K,V>[] table;//HashMap大小, 即HashMap儲存的索引值對數量transient int size; //索引值對的閾值, 用於判斷是否需要擴增雜湊表容量int threshold;//載入因子final float loadFactor; //修改次數, 用於fail-fast機制transient int modCount;
雜湊表的類結構如下,結構就是常見的鏈表結構,其中有屬性:hash值,key索引值,value值,next鏈表下一個值的對象:
/** * Basic hash bin node, used for most entries. (See below for * TreeNode subclass, and in LinkedHashMap for its Entry subclass.) */ 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; } }
HashMap建構函式如下,所有建構函式都會直接或間接實現下面這個主要建構函式的功能:
public HashMap(int initialCapacity, float loadFactor) { //HashMap的初始容量判空 if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " +initialCapacity); //HashMap的初始容量不可超過最大容量 if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; //載入因子,預設為0.75f if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); //初始化載入因子 this.loadFactor = loadFactor; //初始化閾值 this.threshold = tableSizeFor(initialCapacity); }
HashMap存入 方法
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) { //承載當前雜湊表
Node<K,V>[] tab;
//儲存根據雜湊值計算出的雜湊表中下標的Node變數
Node<K,V> p;
int n, i;
//初始化tab為當前雜湊表,並且判空,如果當前雜湊表還為空白,則重新分配 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length;
//如果當前根據雜湊值與表長度算出的該下標的表中Node為空白,則建立Node節點,並存入雜湊表中該下標 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else {//否則,則是該Node的值不為空白 //儲存該下標的雜湊值
Node<K,V> e;
//索引值
K k;
//如果Node的hash值與存入的hash相同,則將當前表中Node變數賦值為e if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode)//如果Node實值型別為TreeNode
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else {//否則,迴圈查詢 for (int binCount = 0; ; ++binCount) {
//從Node值的next開始查詢,如果為空白,則將建立Node節點,並串連到Node的next節點上
if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; }
//如果存入成功,則e的hash值應該與hash相同 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; //迴圈遍曆p的next,p = e即為p=p.next } }
//如果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) //如果表中資料個數+1,如果表中資料個數大於閾值,則重新分配表 resize(); afterNodeInsertion(evict); return null; }
取資料(與存資料類似):
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; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { 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; }