我知道这个问题的答案很容易在互联网上找到.如果我选择不这样做,我需要知道会发生什么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我的代码工作正常.那么,内部发生了什么?
sal*_*ira 26
removeEldestEntry插入元素后始终检查.例如,如果重写方法以始终返回true,则LinkedHashMap将始终为空,因为在每次插入put或putAll插入之后,无论如何都将删除最旧的元素.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
}
我假设您正在学习如何实现缓存。
该方法LinkedHashMap.removeEldestEntry是缓存数据结构中非常常用的一种方法,其中缓存的大小被限制在某个阈值内。在这样的情况下,所述removeEldestEntry方法可以被设置为当尺寸超过阈值(由定义的自动删除最旧的条目MAX_ENTRIES属性) -如在所提供的示例这里。
另一方面,当您以removeEldestEntry这种方式覆盖该方法时,您可以确保在超过阈值时不会发生任何事情MAX_ENTRIES。换句话说,数据结构的行为不像缓存,而是法线贴图。
您的removeEldestEntry方法与 的默认实现相同LinkedHashMap.removeEldestEntry,因此您的 LinkedHashMap 的行为就像普通的 LinkedHashMap 一样,没有重写的方法,保留您放入其中的任何值和键,除非您通过调用remove、removeAll、clear 等显式删除它们使用 LinkedHashMap 的优点是集合视图 ( keySet()、values()、entrySet()) 始终返回迭代器,这些迭代器按照键和/或值添加到 Map 的顺序遍历键和/或值。
| 归档时间: | 
 | 
| 查看次数: | 15037 次 | 
| 最近记录: |