您的位置:首页技术文章
文章详情页

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

浏览:106日期: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
相关文章: