java - HashMap中afterNodeInsertion方法有什么作用呢
仅有的幸福
仅有的幸福 2017-05-17 10:03:41
0
1
856

环境: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-actions
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }

源码中其实已经说了,这个三个方法都是为了继承HashMapLinkedHashMap类服务的。

LinkedHashMapHashMap 的一个子类,它保留插入的顺序,如果需要输出的顺序和输入时的相同,那么就选用 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);
    }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!