HashMap對于每次java開發者來說用的都很多,作為一個coder為了提升自己的代碼能力,花了幾天時間來研究了hashmap 的源碼
1 首先了解一下hashmap 的資料結構

(圖檔來源于網絡,侵權請通知删除)
2代碼中具體的格式為以下代碼,存儲了每個連結清單的頭節點的數組
Node<K,V>[] table
一個Node的數組, 然後看下Node的資料結構
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;
}
實作的Map.Entry的接口,用泛型定義了 key和value的屬性,對于hashMap來說,這就是内部資料的存儲方式,
對hash屬性加上了final 屬性 僅在初始化時指派,同時可以看到next屬性,Node即使上圖中的連結清單節點
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;
}
同時用final修飾了equals方法,分析下具體邏輯
1 判斷兩個對象引用是否相同,如果是,直接傳回
2 判斷該對象是否實作了基礎接口Map.entry 判斷兩個對象的key和value的引用是不是都相同
3 資料put
HashMap的put操作是有傳回值,在業務中可以根據傳回值簡化一些代碼,具體傳回值下面讨論
1 擷取key的hashcode
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
可以看到 取到hashcode後 和自己本身的高16位做了亦或操作,是為了使hashcode的生成更加散列(未了解)
接下來是具體的插入流程
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//判斷hashmap 的table 是否已經進行了初始化,并根據new 時的參數,進行table的初始化
if ((tab = table) == null || (n = tab.length) == 0)
//table 初始化,并擷取node數組的長度,resize函數也承擔了hashmap擴容的功能
n = (tab = resize()).length;
//将新生成的hashcode 和table的長度n-1做&操作,擷取該節點在資料中的下标,如果數組中該位置沒有資料,則根據傳入的值生成新node節點
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {//如果該位置已經存在其他節點(上面if操作已經對p進行了指派,為tab[(n-1)&hash])
Node<K,V> e; K k;
//判斷已經存在的節點資料和新傳入的節點key和hash值是否相同
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)//jdk8紅黑樹特性,暫不了解
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {// 已存在節點的key和新增的key不相同,發生hash沖突
for (int binCount = 0; ; ++binCount) {//将新節點放入該節點連結清單的最後
if ((e = p.next) == null) {//查找到連結清單的最後一個節點後,進行指派操作
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st//在連結清單長度超過一定長度時,将連結清單轉紅黑樹存儲
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))//在将新節點放置在連結清單最後位置後,終止循環
break;
p = e;
}
}
if (e != null) { // existing mapping for key 定位到put資料位置,進行value指派操作
V oldValue = e.value; //擷取key 對應節點的原來資料
if (!onlyIfAbsent || oldValue == null)
e.value = value;//對節點node重新指派
afterNodeAccess(e);
return oldValue; //傳回節點原資料
}
}
//沒有發生hash沖突,數組的某個位置被占用
++modCount;//The number of times this HashMap has been structurally modified, hashMap 結構修改次數
if (++size > threshold)//~~數組已經被占用數量~~ 重新閱讀源碼後發現是hashMap資料量的大小,
//不是被占用數組的大小,自定義類重寫hashCode方法後發現,hashMap中的table數組即使隻占用了少量幾個位置,
//在size到達臨界值後也會進行擴容,即使數組大部分空間被浪得掉,是以hashCode()應該盡量減少hash沖突,減少記憶體浪費
resize();
afterNodeInsertion(evict);.//LinkedHashMap 方法
return null;
}
3 hashmap取資料
首先擷取key的hashcode
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) {// 判斷hashmap是否已經完成初始化,且根據hashcode和數組長度産生的位置值判斷數組中
的該位置是否存在資料
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))//判斷第一個幾點key和hashcode是否相同
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);.//jdk8紅黑樹
do {//循環連結清單查找key和hashcode都符合的節點
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
4hashmap 數組初始化和擴容
在hashMap中 新增一調資料,如果已經占用的位置的數量size/length>DEFAULT_LOAD_FACTOR(0.75) 則會進行數組大小擴容, node[n] 數組的大小預設為16,當已經占用的數量>12時,數組大小會翻倍,是以在使用hashMap時,如果知道key的數量,可以在HashMap初始化時指定數組大小,減少resize()帶來的時間消耗 new HashMap(int n),同時也可以指定擴容因子loadFactor,自行決定擴容時機,
n不是2的次方時,會自動設定為>n的最小2次方值
。
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
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);
}
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;//判斷是初始化還是擴容,擷取node數組長度
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {//判斷為擴容
if (oldCap >= MAXIMUM_CAPACITY) {//判斷數組大小是不是超限
threshold = Integer.MAX_VALUE;
return oldTab; //修改數組最大值為Integer的最大值,傳回原數組
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}//判斷數組長度*2後是否超過最大限定大小
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
//hashmap 數組大小初始化
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;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {// J 如果是擴容,将老數組的資料重新填充到新的node數組中
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)//原節點連結清單隻有一條資料
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)//jdk8 tree
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
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;
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;
}