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

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

问题描述

我想限制一个 HashMap 的最大大小,以获取我正在实现的各种哈希算法的指标。我在 HashMap 的重载构造函数之一中查看了loadfactor。

  HashMap(int initialCapacity,float loadFactor)

我尝试在构造函数中将loadFactor设置为0.0f这意味着我不希望HashMap在EVER中增长)但是 javac 调用这个方法是无效的:



<$ p $ < init>(HashMap.java:177)$ b $在java.util.HashMap中非法加载因子:0.0
< init>(HashMap.java:177)$ b $ < init>(Main.java:20)
at hashtables.Main.main(Main.java:70)Java结果:1
在hashtables.CustomHash中。 / pre>

是否有另一种方法来限制 HashMap 的大小,使其不会增长?

解决方案

c> public class InstrumentedHashMap< K,V>实现Map< K,V> {

私人地图< K,V>地图;

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

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

...
}


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) 

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

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

解决方案

Sometimes simpler is better.

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(...);
             return true;
        }
    }

    ...
}

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

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