Hash Functions
Explore how hash functions work in Java hash tables, including methods like modular arithmetic, truncation, and folding. Understand how these functions compute indices and influence the efficiency of hashing mechanisms in data structures.
We'll cover the following...
🔍 Hash Function?
A hash function simply takes a
keyof an item and returns a calculatedindexin the array for that item.
This index calculation can be a simple or a very complicated encryption method. However, it is very important to choose an efficient Hashing function, as it directly affects the performance of the Hashing mechanism.
What Hash Functions Do?
Have a look at the following illustration to get the analogy of a Hash function.
We can consider the Hash function as a method that takes key as an input and returns the corresponding index to that key.
Commonly Used Hash Functions
These are the most common hashing functions in use:
-
Arithmetic Modular
Take mod of the key with the size of an array (called table)
Hence, the index will always stay between 0 and tableSize - 1.
-
Truncation
Select a part of the key as the index rather than the whole key. Once again, we can use a mod function for this operation, although it does not need to be based on the list size:
-
Folding
Divide the key into smaller chunks and apply different strategies at each chunk. For example, you can add the divided chunks and re-build a different Hashed key: