LinkedHashMap.removeEldestEntry有什么用?

时间:2013-12-25 12:37:55

标签: java collections

我知道这个问题的答案很容易在互联网上找到。如果我选择不removeEldestEntry,我需要知道会发生什么。以下是我的代码:

package collection;

import java.util.*;

public class MyLinkedHashMap {

   private static final int MAX_ENTRIES = 2;

   public static void main(String[] args) {
      LinkedHashMap lhm = new LinkedHashMap(MAX_ENTRIES, 0.75F, false) {

         protected boolean removeEldestEntry(Map.Entry eldest) {
            return false;
         }
      };
      lhm.put(0, "H");
      lhm.put(1, "E");
      lhm.put(2, "L");
      lhm.put(3, "L");
      lhm.put(4, "O");

      System.out.println("" + lhm);

   }
}

即使我不允许removeEldestEntry我的代码正常工作。 那么,内部发生了什么?

4 个答案:

答案 0 :(得分:24)

插入元素后,始终会检查

removeEldestEntry。例如,如果重写方法以始终返回true,则LinkedHashMap将始终为空,因为在每次插入putputAll之后,无论如何都将删除最旧的元素。 JavaDoc显示了一个关于如何使用它的非常明智的例子:

protected boolean removeEldestEntry(Map.Entry eldest){
    return size() > MAX_SIZE;
}

另一种方法是,如果条目不重要,您可能只想删除条目:

protected boolean removeEldestEntry(Map.Entry eldest){
    if(size() > MAX_ENTRIES){
       if(isImportant(eldest)){
          //Handle an important entry here, like reinserting it to the back of the list
          this.remove(eldest.getKey());
          this.put(eldest.getKey(), eldest.getValue());
          //removeEldestEntry will be called again, now with the next entry
          //so the size should not exceed the MAX_ENTRIES value
          //WARNING: If every element is important, this will loop indefinetly!
       } else {
           return true; //Element is unimportant
       }
    return false; //Size not reached or eldest element was already handled otherwise
}

答案 1 :(得分:14)

为什么人们不能回答OP这个简单的问题!

如果removeEldestEntry返回false,则不会从地图中移除任何项目,它基本上会像普通Map一样。

答案 2 :(得分:3)

您的removeEldestEntry方法与LinkedHashMap.removeEldestEntry的默认实现相同,因此您的LinkedHashMap的行为就像普通的LinkedHashMap一样,没有被覆盖的方法,保留您所关注的任何内容和键,除非直到你通过调用remove,removeAll,clear等来显式删除它们。使用LinkedHashMap的好处是集合视图(keySet()values()entrySet())总是返回遍历键的迭代器和/或按照添加到地图的顺序中的值。

答案 3 :(得分:3)

扩展the answer by DavidNewcomb

我假设你正在学习如何实现缓存。

方法LinkedHashMap.removeEldestEntry是一种在缓存数据结构中非常常用的方法,其中缓存的大小限制在某个阈值。在这种情况下,可以将removeEldestEntry方法设置为在大小超过阈值(由MAX_ENTRIES属性定义)时自动删除最旧的条目 - 如提供的示例here。 / p>

另一方面,当您以这种方式覆盖removeEldestEntry方法时,您确保在超出MAX_ENTRIES阈值时什么都不会发生。换句话说,数据结构的行为不像缓存,而是普通的地图。