andandandand andandandand - 4 years ago 367
Java Question

Limiting the max size of a HashMap in Java

I want to limit the maximum size of a

to take metrics on a variety of hashing algorithms that I'm implementing. I looked at the loadfactor in one of
'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
calls this invalid:

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

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

Answer Source

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 {
             return true;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download