11.1: Exercise 9

Think Data Structures - Algorithms and Information Retrieval in Java · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    11.1: Exercise 9

    In MyHashMap.java, I provide the outline of a hash table that grows when needed. Here’s the beginning of the definition:

    public class MyHashMap<K, V> extends MyBetterMap<K, V> implements Map<K, V> {
    
        // average number of entries per sub-map before we rehash
        private static final double FACTOR = 1.0;
    
        @Override
        public V put(K key, V value) {
            V oldValue = super.put(key, value);
    
            // check if the number of elements per sub-map exceeds the threshold
            if (size() > maps.size() * FACTOR) {
                rehash();
            }
            return oldValue;
        }
    }
    

    MyHashMap extends MyBetterMap, so it inherits the methods defined there. The only method it overrides is put which calls put in the superclass — that is, it calls the version of put in MyBetterMap — and then it checks whether it has to rehash. Calling size returns the total number of entries, n. Calling maps.size returns the number of embedded maps, k.

    The constant FACTOR, which is called the load factor, determines the maximum number of entries per sub-map, on average. If \( n > (k * FACTOR) \), that means \( \dfrac{n}{k} > FACTOR \), which means the number of entries per sub-map exceeds the threshold, so we call rehash.

    Run ant build to compile the source files. Then run ant MyHashMapTest. It should fail because the implementation of rehash throws an exception. Your job is to fill it in.

    Fill in the body of rehash to collect the entries in the table, resize the table, and then put the entries back in. I provide two methods that might come in handy: MyBetterMap.makeMaps and MyLinearMap.getEntries. Your solution should double the number of maps, k, each time it is called.


    This page titled 11.1: Exercise 9 was last modified on Sun, 01 Aug 2021 16:55:57 GMT and is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .