Hashing
The Core Concept: Hashing
Both Hash Maps and Hash Sets use a technique called hashing to achieve near-instant lookups.
What is Hashing?
Hashing is the process of taking an input (the key) and converting it into a fixed-size numerical value (the hash code or hash value). This hash code is then used as an index into an underlying array, where the data is stored.
Hash Function: A mathematical function that converts the key into an integer. For example, for a string "ABC," the hash function might calculate the sum of the ASCII values of 'A', 'B', and 'C'.
Index Calculation: Since the hash code can be very large, it is typically reduced to a valid index using the modulo operator (%) with the size of the underlying array (e.g., index = hash_code % array_size).
The Goal of a Good Hash Function
The primary goal is to minimize collisions. A collision occurs when two different keys map to the same array index.
Comments
Post a Comment