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?
淡淡烟草味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 HashMap
的LinkedHashMap
class services.
LinkedHashMap
是HashMap
的一个子类,它保留插入的顺序,如果需要输出的顺序和输入时的相同,那么就选用LinkedHashMap
.
LinkedHashMap
中被覆盖的afterNodeInsertion
Method, 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);
}
}