您的位置:首頁技術文章
文章詳情頁

java - HashMap中afterNodeInsertion方法有什么作用呢

瀏覽:102日期:2023-12-08 11:00:55

問題描述

環境:jdk1.8問題:學習HashMap的時候發現在putVal方法的最后調用了afterNodeInsertion方法

... ++modCount; if (++size > threshold)resize(); afterNodeInsertion(evict); return null;

又去搜索一下afterNodeInsertion方法,發現不少地方都調用了它,但是它的實現卻是

void afterNodeInsertion(boolean evict) { }

一個空方法??想知道這個方法到底有什么作用呢?

問題解答

回答1:

// Callbacks to allow LinkedHashMap post-actionsvoid afterNodeAccess(Node<K,V> p) { }void afterNodeInsertion(boolean evict) { }void afterNodeRemoval(Node<K,V> p) { }

源碼中其實已經說了,這個三個方法都是為了繼承HashMap的LinkedHashMap類服務的。

LinkedHashMap 是 HashMap 的一個子類,它保留插入的順序,如果需要輸出的順序和輸入時的相同,那么就選用 LinkedHashMap。

LinkedHashMap中被覆蓋的afterNodeInsertion方法,用來回調移除最早放入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); }}

標簽: java
相關文章:
国产综合久久一区二区三区