在查看 HashMap 类时,我遇到了这个方法:-
/**
* This method is invoked whenever the value in an entry is
* overwritten by an invocation of put(k,v) for a key k that's already
* in the HashMap.
*/
void recordAccess(HashMap<K,V> m) {
}
其实这个方法是在Entry<K, V>
的内部类里面定义的
我无法理解该评论。这个方法有什么作用?
PS:我还可以看到在 HashMap 的 putForNullKey() 方法中调用了这个方法
private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this); // call
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}
更新:我更新了第一个代码片段。
最佳答案
LinkedHashMap 可以有两个顺序:插入顺序或访问顺序。如果使用访问顺序,此方法确保访问的条目移动到列表的开头。
关于java - 在 Entry<K, V> 类中使用 recordAccess(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17703668/