2013-07-17 23 views
1

虽然在看看HashMap类里面,我碰到这种方法来: -条目<K, V>类使用recordAccess(本)的

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

更新:我已经更新了第一代码片段。

回答

4

LinkedHashMap可以有两个顺序:插入顺序或访问顺序。如果使用访问顺序,则此方法可确保将访问的条目移至列表的开头。

+0

请您详细说明一下吗?为什么从HashMap的方法中调用它? – tmgr

+1

这是一个实现细节。为了使HashMap和LinkedHashMap之间的代码相互关联,基础Map.Entry定义了这个方法(默认情况下什么都不做),并且HashMap调用它。在LinkedHashMap中,此方法被覆盖以维护访问顺序。 –

+0

检查我的编辑。在HashMap的Entry内部类中,recordAccess()是一个无所事事的方法。 – tmgr