Limiting the max size of a HashMap in Java

后端 未结 6 1747
时光说笑
时光说笑 2020-11-29 01:50

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

6条回答
  •  旧时难觅i
    2020-11-29 02:08

    The method put in the HashMap class is the one in charge of adding the elements into the HashMap and it does it by calling a method named addEntry which code is as follows:

       void addEntry(int hash, K key, V value, int bucketIndex) {
            Entry e = table[bucketIndex];
            table[bucketIndex] = new Entry(hash, key, value, e);
            if (size++ >= threshold)
                resize(2 * table.length);
        } 
    

    As you can see in this method is where the HashMap is resized if the threshold has been exceeded, so I would try extending the class HashMap and writing my own methods for put and addEntry in order to remove the resizing. Something like:

    package java.util;
    
    public class MyHashMap extends HashMap {
    
    
        private V myPutForNullKey(V value) {
            for (Entry e = table[0]; e != null; e = e.next) {
                if (e.key == null) {
                    V oldValue = e.value;
                    e.value = value;
                    e.recordAccess(this);
                    return oldValue;
                }
            }
            modCount++;
            myAddEntry(0, null, value, 0);
            return null;
        }
    
        public V myPut(K key, V value) {
            if (key == null)
                return myPutForNullKey(value);
            if (size < table.length) { 
                int hash = hash(key.hashCode());
                int i = indexFor(hash, table.length);
                for (Entry e = table[i]; e != null; e = e.next) {
                    Object k;
                    if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                        V oldValue = e.value;
                        e.value = value;
                        e.recordAccess(this);
                        return oldValue;
                    }
                }
    
                modCount++;
                myAddEntry(hash, key, value, i);
            }
            return null;
        }
    
        void myAddEntry(int hash, K key, V value, int bucketIndex) {
            Entry e = table[bucketIndex];
            table[bucketIndex] = new Entry(hash, key, value, e);
            size++;
        }
    }
    

    You would need to write your own methods since put and addEntry cannot be overriding and you would also need to do the same for putForNullKey since it is called inside put. A validation in put is required to verify that we are not trying to put an object if the table is full.

提交回复
热议问题