search

Home  >  Q&A  >  body text

java - What is the role of the afterNodeInsertion method in HashMap?

Environment: jdk1.8
Problem: When learning HashMap, I found that the afterNodeInsertion method was called at the end of the putVal method

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

I searched for the afterNodeInsertion method again and found that it is called in many places, but its implementation is

    void afterNodeInsertion(boolean evict) { }

An empty method? ? Want to know what this method does?

仅有的幸福仅有的幸福2772 days ago963

reply all(1)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-17 10:05:41

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

    In fact, it has been mentioned in the source code that these three methods are all for inheriting HashMapLinkedHashMap class services.

    LinkedHashMapHashMap 的一个子类,它保留插入的顺序,如果需要输出的顺序和输入时的相同,那么就选用 LinkedHashMap.

    LinkedHashMap中被覆盖的afterNodeInsertionMethod, used to callback to remove the earliest object placed in the 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);
        }
    }

    reply
    0
  • Cancelreply