環(huán)境:jdk1.8
問題:學(xué)習(xí)HashMap的時(shí)候發(fā)現(xiàn)在putVal方法的最後呼叫了afterNodeInsertion方法
...
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
又去搜尋一下afterNodeInsertion方法,發(fā)現(xiàn)不少地方都呼叫了它,但是它的實(shí)作卻是
void afterNodeInsertion(boolean evict) { }
一個(gè)空方法? ?想知道這個(gè)方法到底有什麼作用呢?
// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }
源碼中其實(shí)已經(jīng)說了,這個(gè)三個(gè)方法都是為了繼承HashMap
的LinkedHashMap
類別服務(wù)的。
LinkedHashMap
是HashMap
的一個(gè)子類,它保留插入的順序,如果需要輸出的順序和輸入時(shí)的相同,那么就選用LinkedHashMap
。
LinkedHashMap
中被覆蓋的afterNodeInsertion
方法,用來回調(diào)移除最早放入Map的物件
void afterNodeInsertion(boolean evict) { // possibly remove eldest
LinkedHashMap.Entry<K,V> first;
if (evict && (first = head) != null && removeEldestEntry(first)) {
K key = first.key;
removeNode(hash(key), key, null, false, true);
}
}