- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当我使用 removeEldestEntry(Map.Entry eldest)
实现 LRU 缓存时 removeEldestEntry(Map.Entry eldest)
不起作用。
预期输出= 1,-1,2
实际输出 = 1,1,2
这里 set 方法放置条目,get 检索条目(如果存在),否则返回 -1:
import java.util.*;
import java.lang.*;
import java.io.*;
class LRUCache extends LinkedHashMap {
int capacity;
LinkedHashMap map = new LinkedHashMap(capacity ,1.1f,true);
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if(map.containsKey(key)) {
return (int) map.get(key);
}
return -1;
}
public void set(int key, int value) {
map.put(key,value);
}
protected boolean removeEldestEntry(Map.Entry eldest) {
return map.size()>capacity;
}
public static void main(String args[]) {
LRUCache lru=new LRUCache(1);
int temp;
lru.set(2,1);
temp=lru.get(2);
System.out.println(temp);
lru.set(3,2);
temp=lru.get(2);
System.out.println(temp);
temp=lru.get(3);
System.out.println(temp);
}
}
最佳答案
您的removeEldestEntry
从未被使用过。为了使用您的 removeEldestEntry
,您的类必须扩展 LinkedHashMap
并且您应该覆盖 LinkedHashMap
的 removeEldestEntry
.
如果您使用 LinkedHashMap
作为缓存,它将使用 removeEldestEntry
的默认实现,即:
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return false;
}
关于java-removeEldestEntry(Map.Entry eldest) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31700446/
如何覆盖 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
我是一名优秀的程序员,十分优秀!