Venkat Loganathan Venkat Loganathan - 3 months ago 20x
Java Question

Can rehashing be avoided in hashmap?

My friend was asking me about an interview question today.

Is there a way to prevent /avoid Hashmap? The interviewer gave a clue that there is a hook by which rehashing can be avoided

I tried looking into the HashMap code and looks like as soon as it hits the load factor it rehashes

Setting the load factor to a higher value can only delay the rehashing process

Am confused if at all its possible to prevent rehashing

If someone can point me in the right direction it can help


Yes, it can be avoided if you know the size of your hashmap beforehand.

Set loadFactor = 1 (default value is 0.75)

initialCapacity = size of hashmap + 1 (default value is 16).

Use the following constructor to instantiate your hashmap

public HashMap(int initialCapacity, float loadFactor) 

This will work because in the below code snippet from the HashMap class, the condition (size >= threshold) will never be satisfied, so the hashtable is never resized.

void addEntry(int paramInt1, K paramK, V paramV, int paramInt2)
    if ((size >= threshold) && (null != table[paramInt2]))
        resize(2 * table.length);
        paramInt1 = null != paramK ? hash(paramK) : 0;
        paramInt2 = indexFor(paramInt1, table.length);
    createEntry(paramInt1, paramK, paramV, paramInt2);