![](/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.