如何限制java哈希表中的条目数? [英] How do I limit the number of entries in a java hashtable?

查看:103
本文介绍了如何限制java哈希表中的条目数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a technique such that I can specify a number n such that when the (n + 1)th entry is inserted, the oldest entry is removed first ensuring that the size of the hashtable is always limited to n?

推荐答案

LinkedHashMap 就是这样做的,请参阅 removeEldestEntry 方法。

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;
        }
    };

这篇关于如何限制java哈希表中的条目数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆