![](/img/trans.png)
[英]What is the point of the Map.Entry parameter to LinkedHashMap#removeEldestEntry?
[英]java - removeEldestEntry(Map.Entry eldest) not working
当我使用removeEldestEntry(Map.Entry eldest)
实现LRU缓存时, removeEldestEntry(Map.Entry eldest)
不起作用。
预期输出= 1,-1,2
实际输出= 1,1,2
这里的set方法放置entry,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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.