java数据访问策略_java – 支持基于最近访问过的项目的高效启动策略的数据结构...

我需要一个数据结构,以支持最长时间前请求的项目的最有效的启动策略.例如,我有一堆不时要求的物品.当我内存不足时,我想踢出我数据结构中最古老的项目(哈希映射).

我在想像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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值