- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我知道这个问题的答案很容易在互联网上找到。我需要知道如果我选择不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
我的代码工作正常。那么,内部发生了什么?
最佳答案
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
}
关于java - LinkedHashMap.removeEldestEntry 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20772869/
如何覆盖 removeEldestEntry 方法以将最早的条目保存到文件中?还有如何限制文件的大小,就像我在 LinkedHashMap 中所做的那样。这是代码: import java.util.
我有一个扩展 LinkedHashMap 的类,我将其用作缓存。该缓存有一个属性,该属性定义允许缓存存储的最大大小(以字节为单位)。我对存储的对象的大小进行了粗略估计。 我重写 put,以便更新缓存当
我知道这个问题的答案很容易在互联网上找到。我需要知道如果我选择不removeEldestEntry 会发生什么。以下是我的代码: package collection; import java.uti
考虑这个初始化 this.cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) { public boolean remov
当我使用 removeEldestEntry(Map.Entry eldest) 实现 LRU 缓存时 removeEldestEntry(Map.Entry eldest) 不起作用。 预期输出=
我看了这个帖子:LinkedHashMap removeEldestEntry: How many elements are removed? 它指出 removeEldestEntry 仅删除 1
LinkedHashMap 看起来很适合实现 LRU 缓存。它在链表管理和非线程安全方面有一些开销,但它简化了实现,我可以在我的代码中处理这些。 我的问题是,如果实现 removeEldestEntr
错误看起来像这样 Exception in thread "Thread-1" java.lang.NullPointerException at java.util.LinkedHashMa
我是一名优秀的程序员,十分优秀!