简体   繁体   中英

Hashmap hashcode to internal table index conversion

Hashmaps usually implemented using internal array (table) of buckets. On accessing hashmap by key, we get key's hashcode using key-type specific(logic type specific) hash function. Then we need to map hashcode to actual internal buckets table index.

 key -> (hash function) -> hashcode -> (???) -> index in internal table

Sometimes internal table could shrink and expand, depending on hashmap filling ratio. Then probably hashcode->index conversion method could be changed a bit.

For example our hash function returns 32 bit unsigned integer value and

moment A: internal table has capacity 10000

moment B: internal table has capacity 100000

What algorithms or approach usually used to perform hashcode->internal table index conversion? How is table resizing isue solved for them?

Usually, a simple modulo will do the job.

To take a quick example from Wikipedia , it's simple as that :

hash = hashfunc(key)
index = hash % array_size

As you said, the resizing happen dependending on the hashmap filling ratio. The array is reallocated (see realloc() ), then the indices are recalculated given the new array size, and the values copied to their new index.

I wrote about this here and here .

When you increase the size of your vector of indeces you can be sure that the algorithm that worked well on the shorter vector will work less well on the longer. It is possible to test beforehand and have new algorithms to put in place when you make the vector longer. Or, as the the number of occupied indeces in the current vector increases, have a background, lower-priority thread that tests different algorithms on the data.

As the example in one of my answers shows, a "new algorithm" need be nothing more than a different pair of matched prime numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM