什么样的数据结构类似于哈希表,但是不常用的键会被删除?
问题内容:
我正在寻找一种操作类似于哈希表的数据结构,但是该表具有大小限制。当哈希中的项目数达到大小限制时,应调用剔除函数以摆脱表中检索最少的键/值对。
这是我正在处理的一些伪代码:
class MyClass {
private Map<Integer, Integer> cache = new HashMap<Integer, Integer>();
public int myFunc(int n) {
if(cache.containsKey(n))
return cache.get(n);
int next = . . . ; //some complicated math. guaranteed next != n.
int ret = 1 + myFunc(next);
cache.put(n, ret);
return ret;
}
}
什么情况是,有一些价值n
的,其myFunc()
将被称为很多次,但许多其他值n
将只计算一次。因此,缓存可以填充数百万个不再需要的值。我想为缓存提供一种自动删除不经常检索的元素的方法。
感觉这是一个必须已经解决的问题,但是我不确定我将用来高效地执行什么数据结构。谁能指出我正确的方向?
更新 我知道这必须是一个已经解决的问题。它被称为LRU缓存,可以通过扩展LinkedHashMap类来轻松实现。以下是合并解决方案的代码:
class MyClass {
private final static int SIZE_LIMIT = 1000;
private Map<Integer, Integer> cache =
new LinkedHashMap<Integer, Integer>(16, 0.75f, true) {
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest)
{
return size() > SIZE_LIMIT;
}
};
public int myFunc(int n) {
if(cache.containsKey(n))
return cache.get(n);
int next = . . . ; //some complicated math. guaranteed next != n.
int ret = 1 + myFunc(next);
cache.put(n, ret);
return ret;
}
}
问题答案:
您正在寻找LRUList
/ Map
。签出LinkedHashMap
:
removeEldestEntry(Map.Entry)
可以重写该方法,以强加一个策略,以便在将新映射添加到地图时自动删除陈旧的映射。