简体   繁体   中英

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.

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? Here's a blog post on one based on 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.

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. :)

You may want to consider using Apache Collections. They have a bunch of LRU implementations. 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,然后不必担心缓存的大小。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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