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

查看:1010
本文介绍了java - HashMap中afterNodeInsertion方法有什么作用呢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

环境:jdk1.8
问题:学习HashMap的时候发现在putVal方法的最后调用了afterNodeInsertion方法

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

又去搜索一下afterNodeInsertion方法,发现不少地方都调用了它,但是它的实现却是

    void afterNodeInsertion(boolean evict) { }

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

解决方案

// 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);
    }
}

这篇关于java - HashMap中afterNodeInsertion方法有什么作用呢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆