在 Java 中限制 HashMap 的最大大小 [英] Limiting the max size of a HashMap in Java

查看:33
本文介绍了在 Java 中限制 HashMap 的最大大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想限制 HashMap 的最大大小,以便对我正在实施的各种散列算法进行度量.我查看了 HashMap 的一个重载构造函数中的负载因子.

I want to limit the maximum size of a HashMap to take metrics on a variety of hashing algorithms that I'm implementing. I looked at the loadfactor in one of HashMap's overloaded constructors.

HashMap(int initialCapacity, float loadFactor) 

我尝试在构造函数中将 loadFactor 设置为 0.0f(这意味着我不希望 HashMap 的大小永远增长)但是 javac 认为这是无效的:

I tried setting the loadFactor to 0.0f in the constructor (meaning that I don't want the HashMap to grow in size EVER) but javac calls this invalid:

Exception in thread "main" java.lang.IllegalArgumentException: Illegal load factor: 0.0
        at java.util.HashMap.<init>(HashMap.java:177)
        at hashtables.CustomHash.<init>(Main.java:20)
        at hashtables.Main.main(Main.java:70) Java Result: 1

还有其他方法可以限制 HashMap 的大小,使其永远不会增长吗?

Is there another way to limit the size of HashMap so it doesn't grow ever?

推荐答案

有时候越简单越好.

public class InstrumentedHashMap<K, V> implements Map<K, V> {

    private Map<K, V> map;

    public InstrumentedHashMap() {
        map = new HashMap<K, V>();
    }

    public boolean put(K key, V value) {
        if (map.size() >= MAX && !map.containsKey(key)) {
             return false;
        } else {
             map.put(key, value);
             return true;
        }
    }

    ...
}

这篇关于在 Java 中限制 HashMap 的最大大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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