简体   繁体   English

如何限制java哈希表中的条目数?

[英]How do I limit the number of entries in a java hashtable?

是否有一种技术可以指定一个数字n,这样当插入第(n + 1)个条目时,首先删除最旧的条目,确保哈希表的大小始终限制为n?

LinkedHashMap does exactly that, see javadoc for the removeEldestEntry method. LinkedHashMap就是这样做的,请参阅removeEldestEntry方法的javadoc。

Something like this should do the trick, this will remove the oldest inserted entry: 像这样的东西应该做的伎俩,这将删除最旧的插入条目:

Map map = new LinkedHashMap() {
    @Override
    protected boolean removeEldestEntry(Entry eldest) {
        return size() > N;
    }
};

You can also remove oldest accessed entry by specifying it in the constructor: 您还可以通过在构造函数中指定它来删除最早访问的条目:

    Map map = new LinkedHashMap(16, 0.75f, true) {
        @Override
        protected boolean removeEldestEntry(Entry eldest) {
            return size() > N;
        }
    };

You're looking for a LRU cache perhaps? 您正在寻找LRU缓存吗? Here's a blog post on one based on LinkedHashMap . 这是一篇基于LinkedHashMap的博客文章。

If you have concurrency needs, don't try to solve this problem yourself. 如果您有并发需求,请不要尝试自己解决此问题。 Guava's CacheBuilder has a .maximumSize() method that allows you to limit the size of a map, although it's my understanding that old entries may be cleaned out before you actually reach the limit. Guava的CacheBuilder有一个.maximumSize()方法,允许你限制地图的大小,虽然我的理解是在实际达到限制之前可以清除旧条目。

There's an interesting page on the data structure's design, which should impress on the reader how difficult it would be to do any better than Google's implementation. 一个关于数据结构设计的有趣页面 ,这应该给读者留下了比Google的实现更难做的事情。 :) :)

You may want to consider using Apache Collections. 您可能需要考虑使用Apache Collections。 They have a bunch of LRU implementations. 他们有一堆LRU实现。 Otherwise, you can easily write a similar wrapper for the standard library collections; 否则,您可以轻松地为标准库集合编写类似的包装器; I don't think there's one you can use directly. 我不认为有一个你可以直接使用。

您可以使用双端队列或Deque ,只需在最大计数时删除第一个项目。

如果您正在缓存,可以使用WeakHashMap或WeakReference,然后不必担心缓存的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM