我需要一个数据结构,以支持最长时间前请求的项目的最有效的启动策略.例如,我有一堆不时要求的物品.当我内存不足时,我想踢出我数据结构中最古老的项目(哈希映射).
我在想像Queue这样的FIFO ds,但我不知道如何处理这种情况:
–> a b c d a –>
a是最古老和最新的项目.如果再次添加“a”,我需要搜索整个队列来删除它.这是非常低效的,但我想不出任何有效的方法.也许是某种树形结构,将最少访问的树结构保持在顶部?
Java中是否有任何这种数据结构的实现?
解决方法:
LinkedHashMap是您追求的结构.从the docs开始:
A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches.
Map map = new LinkedHashMap<>(CAPACITY, LOAD_FACTOR, true);
boolean参数确定映射是访问顺序还是插入顺序. true表示访问顺序.
此外,如果您希望地图作为LRU缓存工作,您可以创建自己的类来扩展LinkedHashMap并覆盖removeEldestEntry方法.再次,从文档:
The removeEldestEntry(Map.Entry) method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.
这意味着您可以为缓存创建自己的类:
public class Cache extends LinkedHashMap {
private static final int MAX_ENTRIES = 100;
public Cache() {
super(SOME_INITIAL_CAPACITY, SOME_LOAD_FACTOR, true);
}
protected boolean removeEldestEntry(Entry entry) {
return size() > MAX_ENTRIES;
}
}
用法:
Map map = new Cache<>();
标签:java,data-structures
来源: https://codeday.me/bug/20190827/1746084.html